【发布时间】:2020-08-27 08:49:06
【问题描述】:
我创建了一个带有子组件的组件,该子组件使用在父组件中运行的事件。
当我查看状态变化时,它似乎成功了,但是在渲染时,值是未定义的。
父组件:
constructor(props) {
super(props);
this.handleAnswer = this.handleAnswer.bind(this);
this.state = {
showQuestion: false,
showGetStarted: true,
correctAnswerTotal: 0,
question: <Question onAnswer={this.handleAnswer}/>,
emoji: <EmojiView correctQuestionCount="0"/>
};
}
handleAnswer(result) {
let emoji = this.state.emoji;
if (result === true) {
let newVal = this.state.correctTotal + 1;
alert('newVal: ' + newVal); // updates ------------------------
this.setState({ correctTotal: newVal }, () => {
let updatedVal = this.state.correctTotal;
alert('updatedVal: ' + updatedVal); // updates
});
} else {
this.setState({correctTotal : 0});
}
}
render() {
let correctTotal = this.state.correctQuestionCount;
alert('telling it to render with this count:' + correctTotal);
// correctTotal is undefined here -------------------
let emoji = <EmojiView correctQuestionCount={correctTotal}/>;
return (
<div className="App">
<header className="App-header">
<link href="https://fonts.googleapis.com/css2?family=Merriweather:wght@300;400&display=swap" rel="stylesheet"/>
</header>
<p>
{emoji}
</p>
</div>
);
}
子组件:
questionOneClicked = (user) => {
let lastQuestion = this.state.lastQuestion;
if (lastQuestion.correctIndex == 0) {
// TODO: they got it right!
var myQuestionModel = new QuestionModel("unused");
let randomQuestion = myQuestionModel.getRandomQuestion();
this.setState({lastQuestion: randomQuestion});
this.props.onAnswer(true);
} else {
this.props.onAnswer(false);
}
}
constructor(props, onAnswer) {
super(props);
//alert('props: ' + onAnswer);
var myQuestionModel = new QuestionModel("unused");
let randomQuestion = myQuestionModel.getRandomQuestion();
this.state = {
showQuestion: false,
showGetStarted: true,
lastQuestion: randomQuestion,
};
this.questionOneClicked = this.questionOneClicked.bind(this);
}
即使我的警报显示它已更新,为什么在父 render() 中未定义新状态?
【问题讨论】:
-
如何在父组件中调用子组件?状态的哪个部分究竟是未定义的?哪个函数触发了意外行为?
-
@HagaiHarari:handleAnswer 记录成功,但在 render() 中没有更新。 (下)想通了
标签: javascript reactjs