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



我目前在让我的提供者使用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调用的构造有关,这也是我可能遇到问题的原因。我尝试过构建接口类型,但仍然会遇到同样的错误。

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}>

请注意,将类型的名称大写是一种很好的做法,否则很难将它们与变量的名称区分开来。

相关内容

  • 没有找到相关文章

最新更新