网站搜索

javascript - 在 typescript 中使用 useContext 和 useReducer


我刚开始学习TypeScript,并且在实现 React 的 useContext 和 useReducer。我在跟着教程操作,但在我的 reducer 函数中收到了一个错误:参数 'action' 隐式具有 'any' 类型。

reducer 函数

function reducer(state, action) { // error Parameter 'action' implicitly has an 'any' type.
     return { count: state.count + 1 }
}

计数提供者

   const [state, dispatch] = useReducer(reducer, {
    count: 0
   })

答案#1

您必须将操作类型指定为 any 或通过通用形式来指定。如果您想要构建操作结构,您可以创建一个接口。

function reducer(state, action: { [key: string]: string|number }) { // error Parameter 'action' implicitly has an 'any' type.
    return { count: state.count + 1 }
}

答案#2

首先你需要正确输入你的动作创建器:

Actions.ts

export const increment = (
  background: string
): {
  type: "INCREMENT";
  payload: {
    background: string;
  };
} => ({
  type: "INCREMENT",
  payload: {
    background
  }
});

export const decrement = (
  background: string
): {
  type: "DECREMENT";
  payload: {
    background: string;
  };
} => ({
  type: "DECREMENT",
  payload: {
    background
  }
});

export type Action =
  | ReturnType<typeof increment>
  | ReturnType<typeof increment>;

然后在你的 reducer 中,你应该导入你的动作类型:

Reducer.ts

import type { Action } from "./actions";

export const initialState = {
  count: 0
};

export type Store = typeof initialState;

export const reducer = (state: Store, action: Action) => {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    default:
      return state;
  }
};

最后,在你的应用中任何地方使用 useReducer 钩子时:

计数提供者

import type { Store } from "./context/reducer";
import type { Action } from "./context/actions";

const [state, dispatch] = useReducer<React.Reducer<Store, Action>>(
    reducer,
    initialState
  );

你可以在这里阅读更多内容:使用 TypeScript 的判别联合优雅地为 React 的 useReducer 和 Context API 定义类型