我使用React createcontext来保持全局状态-全局状态的两个单独的对象。它正在开发中,但在gatsby构建上失败。
我在gatsby-brower.js和gatsby-ssr.js中都包含了GlobalContextProvider,我不能包含代码,因为该编辑者抱怨“我的帖子主要是代码”。
GlobalContextProvider.js
import React from "react"
import moment from "moment"
const initialState = {
room: 1,
arrivalDate: moment.utc().startOf("d").format(),
departureDate: moment.utc().startOf("d").add(1, "days").format(),
searchResult: false,
available: false,
loading: false,
rate: 0,
totalNight: 0,
totalPrice: 0,
}
const initialUserState = {
email: "",
password: "",
error: false,
errorMessage: "",
user: "",
userId: "",
userName: "",
loading: false,
showBookingProceed: false,
}
export const GlobalStateContext = React.createContext(
initialState,
initialUserState
)
export const GlobalSetContext = React.createContext()
const GlobalContextProvider = ({ children }) => {
const [state, setSearchState] = React.useState(initialState)
const [userState, setUserState] = React.useState(initialUserState)
return (
<GlobalStateContext.Provider value={{ state: state, userState: userState }}>
<GlobalSetContext.Provider
value={{ setSearchState: setSearchState, setUserState: setUserState }}
>
{children}
</GlobalSetContext.Provider>
</GlobalStateContext.Provider>
)
}
export default GlobalContextProvider
layout.js
import React, { useEffect, useContext } from "react"
import classes from "./layout.module.css"
import Header from "./header"
import "./layout.css"
import firebase from "gatsby-plugin-firebase"
import moment from "moment"
import {
GlobalStateContext,
GlobalSetContext,
} from "../context/GlobalContextProvider"
const Layout = props => {
const { userState } = useContext(GlobalStateContext)
const { setSearchState, setUserState } = useContext(GlobalSetContext)
...
return (
<div className={classes.container}>
<div className={classes.content}>
<Header userState={userState.user} handleLogOut={handleLogOut} />
...
它抱怨用户是“未定义的”,但开发时并非如此。一切工作顺利。
希望能有所启发。谢谢