Javascript React上下文提供程序-无法作为函数传递分派
我试图使用react钩子和上下文来实现Javascript React上下文提供程序-无法作为函数传递分派,javascript,reactjs,react-hooks,react-context,Javascript,Reactjs,React Hooks,React Context,我试图使用react钩子和上下文来实现useReducerhook。除了在子组件中未定义分派函数外,所有功能都正常工作: let initialState = { isLoading: false }; let reducer = (state, action) => { switch (action.type) { case "show_loader": return { ...state, isLoading: true }; default:
useReducer
hook。除了在子组件中未定义分派函数外,所有功能都正常工作:
let initialState = {
isLoading: false
};
let reducer = (state, action) => {
switch (action.type) {
case "show_loader":
return { ...state, isLoading: true };
default:
return;
}
};
const AppContext = createContext(initialState);
function AppProvider({ children }) {
const { Provider } = AppContext;
const [state, dispatch] = useReducer(reducer, initialState);
const value = { state, dispatch };
return <Provider value={value}>{children}</Provider>;
}
export { AppContext, AppProvider };
日志为我提供了状态的
{isLoading:false}
,但调度函数返回为未定义
。有人能告诉我这里缺少什么吗?您需要展示更多相关的代码。这在这里很管用:我怀疑你没有把NewFont
作为AppProvider
的孩子,所以它只是接收initialState
,其中不包括dispatch
函数。你需要显示更多涉及的代码。这在这里很管用:我怀疑您没有将NewFont
作为AppProvider
的子对象,因此它只是接收initialState
,其中不包括dispatch
功能。
function NewFont(props){
const {state, dispatch} = useContext(AppContext);
console.log(state, dispatch)
....
}