gpt4 book ai didi

reactjs - 提供程序值的 Typescript React UseReducer 类型错误

转载 作者:行者123 更新时间:2023-12-05 03:54:26 25 4
gpt4 key购买 nike

我目前在使用 Typescript 中的 React Context API 让我的提供者工作时遇到错误,我收到以下错误,

Type '{ state: { hasEnterPressed: boolean; searchQuery: string; }; dispatch: Dispatch<stringAction>; }' 
is missing the following properties from type '{ hasEnterPressed: boolean; searchQuery: string; dispatch:
(state: { hasEnterPressed: boolean; searchQuery: string; }, action: stringAction) =>
{ hasEnterPressed: boolean; searchQuery: string; }; }': hasEnterPressed, searchQuery TS2739

50 |
51 | return (
> 52 | <SearchContext.Provider value={value}>
| ^
53 | {props.children}
54 | </SearchContext.Provider>
55 | )





我认为这与我的 CreateContext 调用的构造有关,这就是我可能遇到问题的原因。我已经尝试构建接口(interface)类型,但我仍然遇到同样的错误。

import React, {useReducer, createContext, Dispatch}  from "react";


export interface Action {
type: string
}

export interface stringAction extends Action {
payload: string
}

export interface reducerState {
hasEnterPressed: boolean
searchQuery: string,
}


const reducer = (state: reducerState, action: stringAction) => {
switch(action.type) {
case "UPDATEKEYPRESS":
return {
...state,
hasEnterPressed: false
};
case "UPDATESEARCHQUERY":
return {
...state,
searchQuery: action.payload
}
default:
throw new Error();
}
}

const initalState: reducerState = {
hasEnterPressed: false,
searchQuery : '',
}


export const SearchContext = createContext<reducerState>(initalState);

export const SearchProvider: React.FC = (props) => {

const [state, dispatch] = useReducer(reducer, initalState)

const value = {state, dispatch}

return (
<SearchContext.Provider value={value}>
{props.children}
</SearchContext.Provider>
)
}

export default SearchProvider;


最佳答案

value你传入的是一个对象{state, dispatch}同时createContext<reducerState>使提供者期望它是 reducerState .

您需要将上下文类型更改为

interface SearchContextValue {
state: reducerState;
dispatch: Dispatch<ReducerAction<typeof reducer>>
}

export const SearchContext = createContext<SearchContextValue>({
state: initalState,
dispatch: () => {} // fake, but it is not possible to provide at this point
});

或者如果您不需要传递调度——传递状态作为值

<SearchContext.Provider value={state}>

请注意,最好将类型名称大写,否则很难将它们与变量名称区分开来。

关于reactjs - 提供程序值的 Typescript React UseReducer 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61033698/

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