Javascript 需要React createContext参数

Javascript 需要React createContext参数,javascript,reactjs,reducers,Javascript,Reactjs,Reducers,我将使用reacts上下文api和reducer。因为我找到了很多方法来实现这一点,而且缺乏文档,我不知道我做得是否正确。 为了建立一个全球国家,我做了以下几点: import {createContext, useReducer} from "react"; import {appReducer} from "../reducers/appReducer"; function lazyInitializer() { return {db: 1

我将使用reacts上下文api和reducer。因为我找到了很多方法来实现这一点,而且缺乏文档,我不知道我做得是否正确。 为了建立一个全球国家,我做了以下几点:

import {createContext, useReducer} from "react";
import {appReducer} from "../reducers/appReducer";


function lazyInitializer() {
    return {db: 1}
}

export const AppContext = createContext(); //Invalid number of arguments, expected 1 (defaultValue)

const AppContextProvider = (props) => {
    const [globalState, appDispatch] = useReducer(appReducer, null, lazyInitializer);
    return (
        <AppContext.Provider value={{globalState, appDispatch}}>
            {props.children}
        </AppContext.Provider>
    )
}
export default AppContextProvider;
从“react”导入{createContext,useReducer};
从“./reducer/appReducer”导入{appReducer}”;
函数lazyInitializer(){
返回{db:1}
}
export const AppContext=createContext()//参数数无效,应为1(默认值)
常量AppContextProvider=(道具)=>{
const[globalState,appDispatch]=useReducer(appeducer,null,懒散初始值设定项);
返回(
{props.children}
)
}
导出默认AppContextProvider;
我是否必须提供
createContext
默认值?这是使用惰性初始化的正确方法吗?它确实能像上面那样工作。如果有更好的解决方案实现全球状态,请告诉我。
顺便说一句,我不想使用Redux来保持项目的简单。

错误清楚地表明它需要一个默认值。我不明白你为什么问这个问题。你有理由不传递默认值吗?我试图理解为什么不传递任何东西就可以工作。默认值是多少?我已经给useReducer函数赋予了相同的值?在一些教程中,它们将其保留为空…似乎最近react对其进行了更改。“defaultValue参数仅在树中组件上方没有匹配的提供程序时使用。此默认值有助于单独测试组件,而无需包装组件。”-无论您想传递给组件什么,以使它们独立工作,我猜只要将
{}
添加到默认值中,您就不会再有错误了