gpt4 book ai didi

reactjs - 在 Typescript 中 react createContext 问题?

转载 作者:搜寻专家 更新时间:2023-10-30 20:41:32 25 4
gpt4 key购买 nike

所以我在使用 React Context + Typescript 时遇到了一个非常奇怪的问题。

Working example

在上面的示例中,您可以看到我正在尝试做的实际工作。本质上,我是在使用新的 useContext 方法管理状态,它运行良好。

但是,当我尝试在我的盒子上执行此操作时,它似乎无法找到通过 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 返回一个错误:state doesn't exist on null。如果我将上下文的 defaultState 设置为 {},则相同。

当然如果我

React.createContext();  

然后 TS 大喊没有提供默认值。

在沙盒中,创建上下文对象的所有 3 个版本都工作正常。

提前感谢您的任何建议。

最佳答案

React.createContextdefaultValue 值出现了应为以下类型:

interface IContextProps {
state: IState;
dispatch: ({type}:{type:string}) => void;
}

一旦为此类型创建了 Context 对象,例如:

export const AdminStore = React.createContext({} as IContextProps);

Provider React 组件不应再提示错误。

以下是更改列表:

admin-store.tsx

import React, { useReducer } from "react";
import { initialState, IState, reducer } from "./reducer";


interface IContextProps {
state: IState;
dispatch: ({type}:{type:string}) => void;
}


export const AdminStore = React.createContext({} as IContextProps);

export function AdminStoreProvider(props: any) {
const [state, dispatch] = useReducer(reducer, initialState);

const value = { state, dispatch };
return (
<AdminStore.Provider value={value}>{props.children}</AdminStore.Provider>
);
}

关于reactjs - 在 Typescript 中 react createContext 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54577865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com