要在React应用中集成GraphQL,可以使用以下步骤:
npm install graphql @apollo/client
src/apollo.js
,并在其中配置Apollo Client:import { ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://your-graphql-endpoint',
cache: new InMemoryCache()
});
export default client;
import { ApolloProvider } from '@apollo/client';
import client from './apollo';
function App() {
return (
<ApolloProvider client={client}>
{/* Your app components */}
</ApolloProvider>
);
}
useQuery
钩子从GraphQL服务器获取数据:import { useQuery, gql } from '@apollo/client';
const GET_DATA = gql`
query {
data {
id
name
}
}
`;
function MyComponent() {
const { loading, error, data } = useQuery(GET_DATA);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
return (
<div>
{data.data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
);
}
useMutation
钩子:import { useMutation, gql } from '@apollo/client';
const ADD_DATA = gql`
mutation {
addData(input: { name: "New Data" }) {
id
name
}
}
`;
function MyComponent() {
const [addData] = useMutation(ADD_DATA);
const handleAddData = () => {
addData();
};
return (
<button onClick={handleAddData}>Add Data</button>
);
}
通过以上步骤,您可以在React应用中集成GraphQL并与服务器进行数据交互。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。