【问题标题】:Typescript React UseReducer Type Error on Provider Value提供者值上的 Typescript React UseReducer 类型错误
【发布时间】: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


    【解决方案1】:

    您传入的value 是一个对象{state, dispatch},而createContext&lt;reducerState&gt; 使提供者期望它是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}>
    

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

    【讨论】:

    • 成功了,谢谢!还要感谢您的标准,我需要在这方面做得更好。
    猜你喜欢
    • 2017-04-01
    • 2020-04-03
    • 2022-11-25
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多