400-060-0103
開發(fā)環(huán)境需要預(yù)先安裝Node.js運(yùn)行環(huán)境與npm包管理工具。通過終端執(zhí)行以下命令創(chuàng)建項(xiàng)目目錄結(jié)構(gòu):
mkdir react-graphql-blogcd react-graphql-blognpm init -y
| 依賴模塊 | 功能說明 | 版本要求 |
|---|---|---|
| next | 服務(wù)端渲染框架 | ^12.0.0 |
| graphql | 數(shù)據(jù)查詢語(yǔ)言 | ^16.0.0 |
| apollo-client | 狀態(tài)管理工具 | ^3.5.0 |
在pages目錄下創(chuàng)建graphql接口配置文件,實(shí)現(xiàn)CosmicJS數(shù)據(jù)源對(duì)接:
const { ApolloClient, InMemoryCache } = require('@apollo/client');const client = new ApolloClient({ uri: 'https://graphql.cosmicjs.com/v1', cache: new InMemoryCache()}); 構(gòu)建博客文章列表組件時(shí),采用React Hooks管理組件狀態(tài):
import { useQuery } from '@apollo/client';const GET_POSTS = gql` query { posts { title content createdAt } }`;function PostList() { const { loading, error, data } = useQuery(GET_POSTS); if (loading) return Loading...
; if (error) return Error :(
; return data.posts.map(({ title, content }) => ( {title}
{content}
));}