Gatsby通關手冊
如何實現Gatsby的全局狀態管理和api調用
一、為什麼要用Gatsby
Gatsby 是一個React 建站框架,它把自己形容為一個“超級迅捷的React靜態站點生成器”(Blazing-fast static site generator for React),對於長期使用React的前端開發者們來說,Gatsby確實是一大利器,其主要優勢是優秀的數據管理方式。然而儘管官方有很詳盡的教程文檔和Demo,但是對於一些新手來說還是有點晦澀難懂的,本文將對如何快速生成Gatsby網站做一個簡單介紹。
二、快速啟動項目
推薦使用Gatsby教程裡的Quick Start,也可以自己慢慢擼文件,主要包括package.json等基本配置文件。下面上文件列表圖。

三、如何進行全局狀態管理
現在大多數的前端項目都是以redux作為全局狀態管理的,不過相對而言我更喜歡React本身的context api來進行狀態管理,主要是redux嵌套太多層,結構比較負責,對於新手也不是很友好,代碼量也很大,所以如果只是一個輕量級的網站我建議使用react hooks,繼續上圖。
//reactContext.jsimportReact,{useReducer,createContext}from'react'import{Map}from'immutable'constContext=createContext()exportdefaultContextconstinitialState={view:{},}constactions={VIEW_SET_IN:'VIEW_SET_IN',}constreducer=(state,action)=>{switch(action.type){caseactions.VIEW_SET_IN:return{...state,view:Map(state.view).setIn(action.path,action.value)}default:returnstate}}exportconstContextProvider=({children})=>{const[state,dispatch]=useReducer(reducer,initialState)constcontextValue={view:Map(state.view),viewSetIn:(path,value)=>{dispatch({type:actions.VIEW_SET_IN,path,value})},}return<Context.Providervalue={contextValue}>{children}</Context.Provider>}//provider.jsimportReactfrom'react'import{ContextProvider}from'reactContext'constwrapRootElement=({element})=>(<ContextProvider>{element}</ContextProvider>)exportdefaultwrapRootElement//gatsby-browser.jsimportReactfrom'react'importRootLayoutfrom'./provider'exportconstwrapRootElement=RootLayout//gatsby-ssr.jsimportReactfrom'react'importRootLayoutfrom'./provider'exportconstwrapRootElement=RootLayout
四、數據的獲取
關於Gatsby的數據獲取,這個就需要一個內容管理和發布系統,我們可以使用Contentful、WordPress或者Netlify等等,也可以使用自己的api啦。免服務器的系統就不多說了,官方都有很詳細的文檔,這裡主要介紹如何使用自己服務器的api來進行數據獲取展示。如果要生成一個動態鏈接,那麼就需要用到Gatsby的createPage方法。
//gatsby-node.jsconstaxios=require('axios')constpath=require('path')constYOUR_API_HOST='https://api.example.com'constget=()=>axios.get(`${YOUR_API_HOST}/data`)constgetData=async()=>{const{data}=awaitget()return{...data}}exports.createPages=async({actions:{createPage}})=>{constallData=awaitgetData()allData.data.forEach((data)=>{createPage({path:`/${data.slug}`,component:path.resolve('./src/components/data.js'),slug:`/${data.slug}`,context:{data},})})}//src/components/data.jsimportReactfrom'react'constData=({pageContext:{data}})=>{return(<div>{data.id}</div>)}exportdefaultData