useReducer使用useContext返回Typescript错误



我试图创建一个保存状态和reducer的上下文。但是它在返回语句上给了我错误信息,我只是不知道该怎么做:

操作符'<'不能应用于'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;
有谁知道我做错了什么吗?由于

EDIT1:谢谢你的主意,我试过扩展对象,但没有帮助,现在有更多的错误。

Compiled with problems:
ERROR in src/utils/context/context.ts
TS1161: Unterminated regular expression literal.
ERROR in src/utils/context/context.ts:19:13
TS2503: Cannot find namespace 'AppContext'.
ERROR in src/utils/context/context.ts:19:33
TS1005: '>' expected.
ERROR in src/utils/context/context.ts:19:33
TS2304: Cannot find name 'value'.
ERROR in src/utils/context/context.ts:19:38
TS1005: ';' expected.
ERROR in src/utils/context/context.ts:20:9
TS1128: Declaration or statement expected.
ERROR in src/utils/context/context.ts:20:12
TS2304: Cannot find name 'currentState'.
ERROR in src/utils/context/context.ts:20:12
TS2695: Left side of comma operator is unused and has no side effects.
ERROR in src/utils/context/context.ts:21:9
TS2304: Cannot find name 'dispatch'.
ERROR in src/utils/context/context.ts:22:6
TS1128: Declaration or statement expected.
ERROR in src/utils/context/context.ts:22:7
TS1128: Declaration or statement expected.
ERROR in src/utils/context/context.ts:22:8
TS1109: Expression expected.
ERROR in src/utils/context/context.ts:22:8
TS2365: Operator '<' cannot be applied to types 'boolean' and 'RegExp'.
ERROR in src/utils/context/context.ts:22:10
TS18004: No value exists in scope for the shorthand property 'children'. Either declare one or provide an initializer.
ERROR in src/utils/context/context.ts:23:1
TS1128: Declaration or statement expected.

您应该打开currentState值:

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

最后将各部分分档解决:上下文,reducer, provider。不知道为什么。

Thanks for ideas

我想问题是在createContext类型中没有reducer成员

相关内容

  • 没有找到相关文章

最新更新