所以我遇到了一个非常奇怪的问题与React上下文+ typescript 。
Working example
在上面的例子中,你可以看到我尝试做的事情实际上是在工作,本质上我是在用新的useContext方法管理状态,它工作得很完美。
但是,当我尝试在我的box上执行此操作时,它似乎找不到通过useReducer传递的状态值。
export function AdminStoreProvider(props: any) {
const [state, dispatch] = useReducer(reducer, initialState);
// state.isAuth is avail here
// state.user is avail here
const value = { state, dispatch };
// value.state.isAuth is avail here
return (
/* value does not contain state once applied to the value prop */
<AdminStore.Provider value={value}>{props.children}
</AdminStore.Provider>
);
}
错误信息:
Type '{ state: { isAuth: boolean; user: string; }; dispatch:
Dispatch<Actions>; }' is missing the following properties from type
'IState': isAuth, user
请记住,我正在使用的代码正是我在我的盒子上使用的,我甚至从沙箱下载了代码并尝试运行它,但它不起作用。
我使用的是VSCode 1.31
我已经设法推断出,如果我改变我创建上下文的方式:
export const AdminStore = React.createContext(initialState);
到
export const AdminStore = React.createContext(null);
value属性不再引发该错误。
但是,现在useContext返回一个错误:状态不存在于null上。如果我将context的defaultState设置为{}也是一样。
当然如果我
React.createContext();
然后TS对没有提供defaultValue大声呼叫。
- 在沙盒中,创建上下文对象的所有3个版本都工作正常。*
提前感谢您的建议。
3条答案
按热度按时间shyt4zoc1#
React.createContext
的defaultValue
值似乎应为以下类型:为该类型创建
Context
对象后,例如:提供程序React组件不应再报告错误。
以下是更改列表:
一米三米一x
qfe3c7zg2#
我有一个有趣的时间与此,所以我想我会分享我想出了什么。
SidebarProps
表示上下文的状态,除了reducer操作之外,其他所有操作基本上都可以按原样使用。下面是一篇很好的文章,解释了完全相同的解决方案(不在TypeScript中):Mixing Hooks and Context Api
lg40wkob3#
当 typescript 把我制服在它应该为我服务的地方时,我的胃就转了。
在这个特殊的例子中,我真的不关心类型,我这样解决它:
下面的方法就可以了:
大多数不使用TS的示例根本不带参数,而且我认为添加超出需要的代码没有任何价值。