我正在使用componentDidUpdate将状态发送到调度。目前我收到错误this.props.handleSubmit is not a function
。当我登录this.props
时,我看不到日志中的函数,即使我是通过mapDispatchToProps传入的。为什么会这样?
组件
import React, { Component } from "react";
import PlayerCard from "../PlayerCard";
import Shuffler from "../Shuffler";
class MatchCard extends Component {
constructor(props) {
super(props);
this.state = {
selected: 0,
winner: "",
};
}
componentDidUpdate(prevState, handleSubmit) {
if (this.state.winner !== prevState.winner) {
this.props.handleSubmit(this.state.winner);
}
}
render(key, players) {
const { handleClick } = this.props;
let arr = this.props.players;
const checkSelected = (value) => {
return !this.state.selected ? value : 0;
};
return (
<div
className={`${
this.state.selected ? "pointer-events-none" : null
} mt-4 mb-4`}
>
<>
<PlayerCard
player={arr[0]}
selected={this.state.selected === 1}
handleClick={() =>
this.setState({ selected: checkSelected(1), winner: arr[0] })
}
handleDispatch={this.handleSubmit}
/>
<PlayerCard
player={arr[1]}
selected={this.state.selected === 2}
handleClick={() =>
this.setState({ selected: checkSelected(2), winner: arr[1] })
}
handleDispatch={this.handleSubmit}
/>
</>
</div>
);
}
}
export default MatchCard;
mapDispatchToProps
import { connect } from "react-redux";
import MatchCard from "./MatchCard";
import { setWinners } from "../../data/actions/state";
const mapDispatchToProps = (dispatch) => ({
handleSubmit: (winner) => dispatch(setWinners(winner)),
});
export default connect(null, mapDispatchToProps)(MatchCard);
PlayerCard
import React, { Component } from "react";
class PlayerCard extends Component {
render() {
return (
<div
key={this.props.key}
className={`bg-${
this.props.selected ? "blue-400" : "red-400"
} h-64 w-64 flex justify-center shadow-xl focus:shadow-outline`}
onClick={this.props.handleClick}
>
<p className="text-white">{this.props.player}</p>
</div>
);
}
}
export default PlayerCard;
首先,您颠倒了componentDidUpdate参数的顺序。应该是prevProps
,然后是prevState
。尽管你可以用其他名字。还要记住,handleSubmit
只是this.props
或prevProps
中的一个道具(不应该将componentDidUpdate
的参数命名为handleSubmit
,这很令人困惑(。
由于这种反转,您的this.state.winner !== prevState.winner
总是false(您称之为prevState
的prevProps
没有winner
属性,因此您的prevState.winner
是undefined
(。
不太确定你的handleDispatch
有什么用,但你传递的this.handleSubmit
不正确:它应该是this.props.handleSubmit
。
也许您得到的this.props.handleSubmit is not a function
错误是从PlayerCard
抛出的。这是有道理的。请详细说明和/或摘录PlayerCard
,以便我们能为您提供帮助。