【发布时间】:2020-11-14 17:25:13
【问题描述】:
我正在尝试使用 useReducer 和 useContext 挂钩设置 React 存储。 React.createContext(defaultValue) 正在使用我的 TS 检查器创建问题。我尝试了一些不同的东西,但本质上,我 createContext(null) 然后在组件 useReducer() 中设置状态和调度,但是当我调用提供者并将值作为 {state, dispatch} 传递时,它没有告诉我“类型'{状态:任何;调度:React.Dispatch;}'不可分配给类型'null'。
我不明白这一点,因为当它出错时,我已经分配了状态和调度,并且值不应再为空。
这是我正在尝试创建的 Context Provider 包装器。
import React, { createContext, useReducer, FC, Dispatch } from 'react';
import storeReducer, { initialState } from './reducer';
import { Action, State } from './types';
import { isNull } from 'util';
const StoreContext = createContext(null);
const StoreProvider:FC = ({ children }) => {
const [state, dispatch] = useReducer(storeReducer, initialState);
const value = {state, dispatch}
return (
<StoreContext.Provider value={value}>
{children}
</StoreContext.Provider>
);
};
export { StoreProvider, StoreContext };
export interface IStoreContext {
dispatch: (action: Action<any>) => {};
state: State;
}
如果我将其保留为简单的 const StoreContext = createContext();,那么它会抱怨 defaultValue 没有被定义。
疯狂的是,我已经从一个旧项目中提取了这个并且编译时没有问题。
【问题讨论】:
标签: reactjs typescript react-hooks