在Gatsby useDispatch中反应Redux钩子“无效的钩子调用”

时间:2019-12-01 21:50:21

标签: reactjs redux react-redux react-hooks gatsby

我正在尝试在Gatsby项目中使用Redux。我过去曾经使用过Redux,但以前从未使用过Hooks。我以为盖茨比可能是个问题,但是我已经能够使用useStaticQuery钩子(如下面的builder.js所示)。我已经检查了所有版本(请参见下文)和规则。

这是我收到的错误:

enter image description here

版本:

纱线清单起反应

react@16.12.0

纱线列表react-redux

react-redux@7.1.3

纱线清单还原

redux@4.0.4

这是我的builder.js代码。

import {graphql, useStaticQuery} from 'gatsby'
import React from "react"
import Armor from './armor'

export default () => {

  const data = useStaticQuery(graphql`
    query Data {
      allArmor(filter: {type: {eq: "chest"}}) {
        totalCount
        nodes {
          name
          attack
          magic
        }
      }
    }`)

  return (
    <div>
      <h1>{data.nodes[0]}</h1>
      <Armor/>
    </div>
  )
}

这是我的armour.js代码。 (这是引发错误的地方)

import React from "react"
import { useDispatch } from 'react-redux'

export default () => {

  const dispatch = useDispatch()

  return (
    <button onClick={() => dispatch({type: 'INCREMENT' })}>Increment</button>
  )
}

Gatsby与Redux相关的代码:

gatsby-browser.js

import wrapWithProvider from './wrap-with-provider'
export const wrapRootElement = wrapWithProvider

gatsby-ssr.js

import wrapWithProvider from './wrap-with-provider'
export const wrapRootElement = wrapWithProvider

wrap-with-provider.js

import React from 'react'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'

import * as reducers from './src/redux/reducers'

const initialState = {
  setCount: 0,
  setTotal: 0,
}

const combinedReducers = combineReducers({ ...reducers })
export default ({ element }) => {
  const store = createStore(combinedReducers, initialState)
  return <Provider store={store}>{element}</Provider>
}

redux / reducers / index.js

const setCount = (state = 0, action) => {
  switch (action.type) {
    case `UPDATE`:
      return action.count

    default:
      return state
  }
}

2 个答案:

答案 0 :(得分:1)

使用redux“就像过去一样”无法立即使用。

您需要setup redux beforehand with gatsby's SSR rendering,即设置gatsby-browswer.jsgatsby-ssr.js

  

要在Gatsby网站中使用Redux,您需要连接到Gatsby的两个扩展点。

     

wrapRootElement中运行一次,该时间在Gatsby服务器呈现过程中运行,而在wrapRootElement中运行一次,它是Gatsby浏览器API的一部分。

     

请查看./gatsby-ssr.js和。/gatsby-browser.js,以了解此示例中的实现方式。

这是因为您使用CRA引导时所使用的入口点与Gatsby中的入口点不同。

答案 1 :(得分:0)

您需要使用如下的react组件再次包装包装器

const FireBaseApp = () => {
const [loggedIn, setLoggedIn] = useState(/* some code */)
  useEffect(() => {
    firebase.auth().onAuthStateChanged(user => {
      setLoggedIn(!!user)
    })
  })
  return (
    <FirebaseContext.Provider value={{ loggedIn }}>
      {element}
    </FirebaseContext.Provider>
  )
}

const Wrapper = ({ element }) => {
  return <FireBaseApp element={element} />
}

exports.wrapRootElement = Wrapper 

来源: https://github.com/gatsbyjs/gatsby/issues/22833#issuecomment-609370401

相关问题