我正在尝试为我正在处理的应用程序编写上下文提供程序,我创建了以下文件:
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:
如果不创建一个反应组件来包装它,就没有办法使用useReducer
?我宁愿通过上下文传递它,因为如果我能帮助它,我真的不想使用 JSX。
当层次结构中没有任何提供程序时,不会使用传递给 createContext 的值。如果您有正确的设置,实际上不需要传递默认值
同样正如错误所暗示的那样,钩子应该在functional components
内部使用,而不是
import React, { createContext, useReducer } from 'react'
import { initialState, playerUiReducer } from './reducers/player-ui'
const PlayerStateContext = createContext();
export default PlayerStateContext
您必须改为将值传递给PlayerContext
提供程序
const App = () => {
const [state, dispatch] = useReducer(playerUiReducer, initialState);
return (
<PlayerStateContext.Provider value={[state, dispatch]}>
{/* code here */}
</PlayerStateContext.Provider>
)
}