【发布时间】:2023-04-08 04:12:01
【问题描述】:
我目前在让我的提供程序在 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;
【问题讨论】:
标签: reactjs typescript react-hooks