>本教程演示了構建一個使用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中文網其他相關文章!