您好,登錄后才能下訂單哦!
要在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。