您好,登錄后才能下訂單哦!
要在React中使用GraphQL,您可以通過使用Apollo或Relay等庫來實現。下面是一個簡單的步驟來使用Apollo在React中實現GraphQL:
npm install @apollo/client graphql
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://your-graphql-endpoint.com',
cache: new InMemoryCache()
});
const App = () => (
<ApolloProvider client={client}>
<YourApp />
</ApolloProvider>
);
import { useQuery, gql } from '@apollo/client';
const GET_BOOKS = gql`
query GetBooks {
books {
id
title
author
}
}
`;
const BooksList = () => {
const { loading, error, data } = useQuery(GET_BOOKS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.books.map(book => (
<li key={book.id}>{book.title} by {book.author}</li>
))}
</ul>
);
};
import { useMutation, gql } from '@apollo/client';
const ADD_BOOK = gql`
mutation AddBook($title: String!, $author: String!) {
addBook(title: $title, author: $author) {
id
title
author
}
}
`;
const AddBookForm = () => {
let titleInput, authorInput;
const [addBook] = useMutation(ADD_BOOK);
const handleSubmit = e => {
e.preventDefault();
addBook({
variables: {
title: titleInput.value,
author: authorInput.value
}
});
titleInput.value = '';
authorInput.value = '';
};
return (
<form onSubmit={handleSubmit}>
<input ref={node => { titleInput = node; }} />
<input ref={node => { authorInput = node; }} />
<button type="submit">Add Book</button>
</form>
);
};
這些步驟向您展示了如何在React中使用Apollo Client來實現GraphQL。您可以根據您的需求和項目來進一步擴展和調整這些示例。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。