我正在尝试为我正在使用的应用程序编写上下文提供程序,我已经创建了以下文件:
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,如果我可以帮助它的话。
发布于 2020-05-27 21:57:07
当层次结构中没有任何提供程序时,不使用传递给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>
)
}https://stackoverflow.com/questions/62044802
复制相似问题