要在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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。