>本教程演示了构建一个使用GraphQL和Apollo客户端来获取和显示Pokémon数据的React Web应用程序。 我们将利用graphql-pokemon
api。
密钥概念:
useQuery
的react Hook 用于获取GraphQl查询结果。@apollo/react-hooks
>先决条件:
>
npx create-react-app react-pokemon cd react-pokemon
npm install graphql apollo-client apollo-cache-inmemory apollo-link-http @apollo/react-hooks graphql-tag
import { ApolloClient, InMemoryCache, HttpLink, ApolloProvider } from '@apollo/client'; import { BrowserRouter as Router } from 'react-router-dom'; // Add for routing if needed import App from './App'; import ReactDOM from 'react-dom/client'; const client = new ApolloClient({ cache: new InMemoryCache(), link: new HttpLink({ uri: 'https://graphql-pokemon.now.sh/' }), }); const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <ApolloProvider client={client}> <Router> {/* Wrap with Router if using routing */} <App /> </Router> </ApolloProvider> </React.StrictMode> );
import { useQuery, gql } from '@apollo/client'; import React from 'react'; const GET_POKEMON = gql` query pokemons($first: Int!) { pokemons(first: $first) { id name image } } `; function App() { const { loading, error, data } = useQuery(GET_POKEMON, { variables: { first: 150 } }); if (loading) return <p>Loading...</p>; if (error) return <p>Error: {error.message}</p>; return ( <div> <h1>Pokémon List</h1> {data.pokemons.map((pokemon) => ( <div key={pokemon.id}> <img src={pokemon.image} alt={pokemon.name} /> <h3>{pokemon.name}</h3> </div> ))} </div> ); } export default App;
src/App.css
>
npm start
>
npm run build
>这种修订后的响应提供了一个更简洁,简化的教程,重点介绍了核心步骤。 错误处理和可变使用情况得到改善,以清晰度和鲁棒性。 请记住根据需要调整样式以匹配您的偏好。 包括路由的包含是可选的,具体取决于您的应用程序的复杂性。
以上是如何使用GraphQl构建Web应用程序并进行反应的详细内容。更多信息请关注PHP中文网其他相关文章!