reactjs Typescript?中的React createContext问题

a0x5cqrl  于 2023-01-02  发布在  React
关注(0)|答案(3)|浏览(291)

所以我遇到了一个非常奇怪的问题与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个版本都工作正常。*

提前感谢您的建议。

shyt4zoc

shyt4zoc1#

React.createContextdefaultValue值似乎应为以下类型:

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

为该类型创建Context对象后,例如:

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

提供程序React组件不应再报告错误。
以下是更改列表:

一米三米一x

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>
  );
}
qfe3c7zg

qfe3c7zg2#

我有一个有趣的时间与此,所以我想我会分享我想出了什么。
SidebarProps表示上下文的状态,除了reducer操作之外,其他所有操作基本上都可以按原样使用。
下面是一篇很好的文章,解释了完全相同的解决方案(不在TypeScript中):Mixing Hooks and Context Api

import React, { createContext, Dispatch, Reducer, useContext, useReducer } from 'react';

interface Actions {
    type: string;
    value: any;
}

interface SidebarProps {
    show: boolean;
    content: JSX.Element | null;
}

interface SidebarProviderProps {
    reducer: Reducer<SidebarProps, Actions>;
    initState: SidebarProps;
}

interface InitContextProps {
    state: SidebarProps;
    dispatch: Dispatch<Actions>;
}

export const SidebarContext = createContext({} as InitContextProps);
export const SidebarProvider: React.FC<SidebarProviderProps> = ({ reducer, initState, children }) => {
    const [state, dispatch] = useReducer(reducer, initState);
    const value = { state, dispatch };
    return (
        <SidebarContext.Provider value={value}>
            {children}
        </SidebarContext.Provider>
    );
};
export const useSidebar = () => useContext(SidebarContext);

const SidebarController: React.FC = ({ children }) => {
    const initState: SidebarProps = {
        show: false,
        content: null
    };

    const reducer: Reducer<SidebarProps, Actions> = (state, action) => {
        switch (action.type) {
            case 'setShow':
                return {
                    ...state,
                    show: action.value
                };

            case 'setContent':
                return {
                    ...state,
                    content: action.value
                };

            default:
                return state;
        }
    };

    return (
        <SidebarProvider reducer={reducer} initState={initState}>
            {children}
        </SidebarProvider>
    );
};

export default SidebarController;
lg40wkob

lg40wkob3#

当 typescript 把我制服在它应该为我服务的地方时,我的胃就转了。
在这个特殊的例子中,我真的不关心类型,我这样解决它:
下面的方法就可以了:

const ctx = createContext<any>({});

大多数不使用TS的示例根本不带参数,而且我认为添加超出需要的代码没有任何价值。

相关问题