【问题标题】:Can not access property from mapDispatchToProps无法从 mapDispatchToProps 访问属性
【发布时间】:2019-06-04 17:44:51
【问题描述】:

我无法从mapDispatchToProps 访问属性,当我使用this.props.updateCar(car) 时它说:

“Readonly &”类型上不存在属性“updateCar” 只读'

这是我的代码:

import * as React from "react";
import { RootState } from "src/reducers";
import { updateCar } from "src/Car/actions";
import { CarState } from "src/Car/reducers";
import { connect } from "react-redux";

const mapStateToProps = (state: RootState) => ({
  car: state.car
});

const mapDispatchToProps = (dispatch: any) => ({
  updateCar: (car: CarState) => dispatch(updateCar(car))
});

type StateProps = ReturnType<typeof mapStateToProps>;
type MapDispatchToProps = typeof mapDispatchToProps;

type Props = StateProps & MapDispatchToProps;

class CarContainer extends React.Component<Props> {
  updateCar = () => {
    const car: CarState = {
      price: 1,
      name: "Mercedes"
    };
    this.props.updateCar(car);
  };

  render() {
    return (
      <div>
        {this.props.car.name}
        <button onClick={this.updateCar}>UPDATE</button>
      </div>
    );
  }
}

export default connect<StateProps, MapDispatchToProps>(
  mapStateToProps,
  mapDispatchToProps
)(CarContainer);

【问题讨论】:

    标签: reactjs typescript redux react-redux


    【解决方案1】:

    您应该像使用 StateProps 一样使用 ReturnType&lt;typeof mapDispatchToProps&gt;

    【讨论】:

    • 不错不错:)。谢谢
    • 如果您将答案标记为正确答案,那就太好了,这样其他人也将能够受益:)
    • 你的代码看起来不错,所以我只能假设它来自你的减速器/动作创建者。
    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 2015-11-21
    • 2014-09-19
    • 2021-11-06
    • 2016-07-12
    • 2014-03-10
    • 2018-04-24
    • 2017-04-25
    相关资源
    最近更新 更多