【问题标题】:React action, ESLint: Argument 'dispatch' should be typed with a non-any type反应动作,ESLint:参数'dispatch'应该用非任何类型输入
【发布时间】:2021-02-10 22:27:51
【问题描述】:

我有一个像这样的React 操作:

export const sigIn = () =>
  async (dispatch: any) => {
    dispatch({
      type: SIGN_IN_REQUEST
    });
  };

我得到一个:

ESLint: Argument 'dispatch' should be typed with a non-any type.(@typescript-eslint/explicit-module-boundary-types)

作为async 上的警告。为什么?

编辑:对于这两个答案,我从 redux 输入了 Dispatch 类型,但我仍然有警告:

【问题讨论】:

    标签: reactjs typescript typescript-typings


    【解决方案1】:

    您可以在 eslint 配置中禁用规则或添加足够的类型。

    import { Dispatch } from 'react-redux';
    
    async (dispatch: Dispatch<{ type: SIGN_IN_REQUEST }>): void => {
       dispatch({
         type: SIGN_IN_REQUEST
    });
    

    【讨论】:

    • @pmiranda 然后在末尾添加void,因为它不返回任何内容。
    【解决方案2】:

    您收到错误是因为您使用了any,并且您的 lint 规则禁止这样做。解决方法是使用正确的 dispatch 类型,可以从 redux 导入:

    import { Dispatch } from 'redux';
    
    export const sigIn = () => 
      async (dispatch: Dispatch) => {
        dispatch({
          type: SIGN_IN_REQUEST
        })
      };
    

    【讨论】:

    • 函数缺少返回类型的解决方法是向函数添加返回类型。看起来应该是Promise&lt;void&gt;
    • 是的,Promive&lt;void&gt; 有效,谢谢。我会选择这个答案作为正确答案,因为是第一个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多