我正在构建具有像这样的喜欢/不喜欢能力的简单 视频
但是当喜欢或不喜欢被拒绝时它不能正常工作,因为在 componentDidUpdate 它会循环,我不知道应该使用什么条件来防止这种情况。这是我的组件:
class PlayingVideo extends Component {
constructor(props) {
super(props);
this.state = {
likedThis: _.includes(this.props.video.likedBy, this.props.user_id),
likedLength: this.props.video.likedBy.length
};
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.likeVideoHasError) {
this.setState({
likedThis: false,
likedLength: this.state.likedLength - 1
});
}
if (this.props.dislikeVideoHasError) {
this.setState({
likedThis: true,
ikedLength: this.state.likedLength + 1
});
}
}
like = () => {
if (this.props.likeVideoPending || this.props.dislikeVideoPending) return;
this.setState({ likedThis: true, likedLength: this.state.likedLength + 1 });
this.props.dispatch(likeVideo(this.props.videoId));
};
dislike = () => {
if (this.props.likeVideoPending || this.props.dislikeVideoPending) return;
this.setState({
likedThis: false,
likedLength: this.state.likedLength - 1
});
this.props.dispatch(dislikeVideo(this.props.videoId));
};
}
const mapStateToProps = (state, ownProps) => {
return {
likeVideoHasError: state.video.likeVideoHasError,
dislikeVideoHasError: state.video.dislikeVideoHasError,
likeVideoPending: state.video.likeVideoPending,
dislikeVideoPending: state.video.dislikeVideoPending
};
};
export default connect(mapStateToProps)(PlayingVideo);