wrapRootElement + contextAPI:页面更改导致提供程序重新呈现,因此重置了状态

时间:2020-03-09 18:09:35

标签: reactjs gatsby react-context

摘要

我正在使用React上下文api和钩子来创建全局的“ StateProvider”,但是当我更改页面时,我的提供者会重​​新渲染,从而导致我失去活动状态并返回默认值。

据我了解,使用wrapRootElement方法应该意味着我的stateProvider应该保持不变。

对于如何调试此问题的一些建议将不胜感激!

相关信息

gatsby-browser.js

const StateProvider = require("./src/components/store/store").StateProvider
exports.wrapRootElement = ({ element }) => {
  return <StateProvider>{element}</StateProvider>
}

store.js

const StateProviderContext = createContext()
const DispatchProviderContext = createContext()

const StateProvider = ({ children }) => {
  console.log("init")
  const tocTree = useEntries()
  const initialState = reducer(
    {},
    {
      type: INIT_PAGE,
      value: { pathname, tocTree },
    }
  )
  const [state, dispatch] = useReducer(reducer, initialState)
  return (
    <StateProviderContext.Provider value={state}>
      <DispatchProviderContext.Provider value={dispatch}>
        {children}
      </DispatchProviderContext.Provider>
    </StateProviderContext.Provider>
  )
}

2 个答案:

答案 0 :(得分:0)

关注https://codesandbox.io/s/soanswer60606158-pfm2b

通常,您需要同时在wrapRootElementgatsby-ssr.js中实现gatsby-browser.js

https://www.gatsbyjs.org/docs/browser-apis/#wrapRootElement

wrapRootElement note

您可以看到我提取了wrapRootElement.js,它被导入到上述两个文件中。

./wrapRootElement.js

import React from "react"
import StateProvider from "./src/components/store/store"

const wrapRootElement = ({ element }) => {
  return <StateProvider>{element}</StateProvider>
}

export default wrapRootElement

gatsby-browser.js

import wrapRootElement from "./wrapRootElement"

export { wrapRootElement }

gatsby-ssr.js

import wrapRootElement from "./wrapRootElement"

export { wrapRootElement }

答案 1 :(得分:-1)

我遇到了同样的问题;更改页面后,状态正在重置。解决我的问题的关键是您应该使用 Gatsby 的 <Link> 来更改页面(我之前使用的是 <a> 标记)。

我的代码现在无需gatsby-ssr.js即可完美运行。