无法从mapDispatchToProps访问属性

时间:2019-06-04 17:44:51

标签: reactjs typescript redux react-redux

使用mapDispatchToProps时,我无法访问this.props.updateCar(car)的属性,它显示:

  

类型“只读和不存在”属性“ updateCar”   Readonly <{children ?: ReactNode; }>'

这是我的代码:

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);

1 个答案:

答案 0 :(得分:1)

您应该像使用ReturnType<typeof mapDispatchToProps>一样使用StateProps