【发布时间】:2018-02-14 16:11:43
【问题描述】:
据我了解,当props 发生更改时,组件将重新渲染,componentWillMount 应在重新渲染之前运行。目前我的构造函数和componentWillMount 按预期运行,但随后问题prop 发生变化,我需要更新用户分数状态,但问题道具的这种变化不会触发构造函数或componentWillMount。由于我不应该更新渲染函数中的状态(到目前为止我唯一能够访问更新的问题prop 的地方),我怎样才能让反应在它的props 中识别这种变化然后更新状态?希望这是可以理解的。
这是我的容器
class FullTimeScoreContainer extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
userHomeScore: 1,
userAwayScore: 1
}
}
componentWillMount() {
getFTSAnswerStatus(this.props.question).then(foundScores => {
if ( foundScores.userHomeScore ) {
this.setState({
userHomeScore: foundScores.userHomeScore,
userAwayScore: foundScores.userAwayScore
});
}
})
}
render() {
const { option, question, questionIndex, user, configs, renderAs, showNextQuestionAfterFTS, total} = this.props;
// check if question is active or not
let ComponentClass;
if ( question[0].active ) {
ComponentClass = FullTimeScoreActive;
} else {
ComponentClass = FullTimeScoreLocked;
}
const changeScoreState = (team, val) => {
switch (team) {
case "home":
this.setState( (prevState) => ({ userHomeScore: prevState.userHomeScore + val }) );
break;
case "away":
this.setState( (prevState) => ({ userAwayScore: prevState.userAwayScore + val }) );
break;
default:
throw new Error("unrecognised team to change score state")
}
}
const onClickCallback = () => {
const p = this.props;
const s = this.state;
p.showNextQuestionAfterFTS();
p.recordFullTimeScoreAnswer(s.userHomeScore, s.userAwayScore, p.question, p.questionIndex, p.user, p.configs)
}
return (
<ComponentClass
imgSrc={imgSrc}
user={user}
answerStatus={answerStatus}
question={question}
onClickCallback={onClickCallback}
questionIndex={questionIndex}
total={total}
configs={configs}
userScores={this.state}
changeScoreState={changeScoreState}
/>
)
}
}
const mapStateToProps = state => {
return {
configs: state.configs,
user: state.user
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ recordFullTimeScoreAnswer, showNextQuestionAfterFTS }, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(FullTimeScoreContainer);
export { FullTimeScoreContainer }
【问题讨论】:
-
我不确定这个问题,但我认为您正在寻找
componentDidMount -
componentDidMount 会比
componentWillMount好用 -
感谢你们的 cmets 伙计们,我都试过了,但没有成功。到问题道具更新时,构造函数和挂载函数的生命周期已经结束
标签: javascript reactjs