首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在“createContext”中使用“useReducer”

在“createContext”中使用“useReducer”
EN

Stack Overflow用户
提问于 2020-05-27 21:53:12
回答 1查看 37关注 0票数 0

我正在尝试为我正在使用的应用程序编写上下文提供程序,我已经创建了以下文件:

代码语言:javascript
复制
import React, { createContext, useReducer } from 'react'
import { initialState, playerUiReducer } from './reducers/player-ui'

const PlayerStateContext = createContext(useReducer(playerUiReducer, initialState))

export default PlayerStateContext

在我用useReducer钩子替换硬编码的数据之前,它工作得很好,但现在它给出了以下错误:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

有没有办法在不创建react组件的情况下使用useReducer?我宁愿通过上下文传递它,因为我真的不想使用JSX,如果我可以帮助它的话。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-27 21:57:07

当层次结构中没有任何提供程序时,不使用传递给createContext的值。如果设置正确,则实际上不需要传递默认值

同样,正如错误所暗示的那样,钩子应该在functional components内使用,而不是在它外部使用

代码语言:javascript
复制
import React, { createContext, useReducer } from 'react'
import { initialState, playerUiReducer } from './reducers/player-ui'

const PlayerStateContext = createContext();

export default PlayerStateContext

您必须将该值传递给PlayerContext提供程序

代码语言:javascript
复制
const App = () => {
   const [state, dispatch] = useReducer(playerUiReducer, initialState);
   return (
      <PlayerStateContext.Provider value={[state, dispatch]}>
          {/* code here */}
      </PlayerStateContext.Provider>
   )
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62044802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档