【问题标题】:useReducer with useContext results with Typescript erroruseReducer with useContext 结果出现 Typescript 错误
【发布时间】:2023-01-23 20:26:56
【问题描述】:

我正在尝试创建一个包含状态和 reducer 的上下文。 但它在 return 语句中给我错误消息,我只是不知道该怎么做:

运算符 '<' 不能应用于类型 'boolean' 和 'RegExp'.ts(2365)
未终止的正则表达式 literal.ts(1161)

import { createContext, FunctionComponent, PropsWithChildren, ReactNode, useReducer } from "react";
import reducer from "./reducer";

// stored data
export type storeType = {
    message: string | null
};

const initialState: storeType = {
    message: null
}

const AppContext = createContext<storeType>(initialState);

const CxtProvider = ({ children }: PropsWithChildren) => {
    const [currentState, dispatch] = useReducer(reducer, initialState);

    return <AppContext.Provider value={{
        currentState,
        dispatch
    }}>{children}</AppContext.Provider>
};

export default CxtProvider;

任何人都知道,我做错了什么?谢谢

【问题讨论】:

  • 你试过用()包装你要退回的东西吗?

标签: reactjs typescript react-hooks react-context use-reducer


【解决方案1】:

您应该打开 currentState 值:

return <AppContext.Provider value={{
          ...currentState,
          dispatch
       }}>{children}</AppContext.Provider>

【讨论】:

    猜你喜欢
    • 2019-12-15
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2019-12-09
    • 1970-01-01
    • 2021-11-13
    • 2020-10-26
    相关资源
    最近更新 更多