【问题标题】:Redux dispatch function and TypeScriptRedux 调度函数和 TypeScript
【发布时间】:2021-02-18 09:48:26
【问题描述】:

有这么简单的React 组件:

import React from 'react';
import { connect } from 'react-redux';
import { INCREMENT, DECREMENT } from '../Misc/actions';

interface Props {
    count: number,
    asd: number
}

class Counter extends React.Component<Props> {
    state = { count: 0 }

    increment = () => {
        this.props.dispatch({ type: "INCREMENT" });
    }

    decrement = () => {
        this.props.dispatch({ type: "DECREMENT" });
    }

    render() {
        ...
        )
    }
}

type ICounterState = {
    count: number
}

function mapStateToProps(state:ICounterState) {
    return {
        count: state.count,
        asd: 78
    };
}

export default connect(mapStateToProps)(Counter);

我收到一个错误:Property 'dispatch' does not exist on type 'Readonly&lt;Props&gt; &amp; Readonly&lt;{ children?: ReactNode; }&gt;'

我肯定是TypeScript 错误但是如何解决这个问题?

【问题讨论】:

  • 您的界面Props 缺少调度。
  • @HMR 好的,我如何输入调度操作?
  • import {Dispatch} from 'react-redux' 然后 dispatch:Dispatch 在接口 Props 中。

标签: reactjs typescript redux react-redux


【解决方案1】:

dispatch 属性添加到Props 接口。由于Dispatch 接口是泛型的,它接受泛型参数,所以你需要使你的Props 泛型接口。

import React from 'react';
import { Dispatch, Action, AnyAction } from 'redux';
import { connect } from 'react-redux';

const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

interface Props<A extends Action = AnyAction> {
  count: number;
  asd: number;
  dispatch: Dispatch<A>;
}

class Counter extends React.Component<Props> {
  state = { count: 0 };

  increment = () => {
    this.props.dispatch<{ type: typeof INCREMENT }>({ type: INCREMENT });
  };

  decrement = () => {
    this.props.dispatch({ type: DECREMENT });
  };

  render() {
    return <div>counter</div>;
  }
}

type ICounterState = {
  count: number;
};

function mapStateToProps(state: ICounterState) {
  return {
    count: state.count,
    asd: 78,
  };
}

export default connect(mapStateToProps)(Counter);

【讨论】:

  • 我会说 Props 上的泛型是没有意义的,因为组件本身将泛型值设置为 any。 redux 或 react-redux 都导出了一个 AnyAction 类型,我将在此处用作操作类型。这比任何都好,因为 AnyAction 始终是一个具有字符串类型属性的对象。
  • @LindaPaiste 感谢您指出这一点。我应该使用默认的泛型参数AnyAction
猜你喜欢
  • 1970-01-01
  • 2021-02-27
  • 2019-01-10
  • 2020-03-25
  • 2017-08-09
  • 1970-01-01
  • 2018-12-10
  • 2020-05-30
  • 2020-02-16
相关资源
最近更新 更多