【发布时间】:2018-06-09 08:13:49
【问题描述】:
我已经创建了组件,该组件将更改其状态的函数传递给子组件。
//parent component
setSubject = (id) => {
this.setState({
currentSubject: id
});
}
<Subjects authToken = {this.state.authToken} subjects = {this.state.subjects} setSubject = {this.setSubject} />
//child component
<li onClick={() => this.props.setSubject(subject.id)}>Egzamino programa</li>
该状态被传递给另一个组件。
<Sections authToken = {this.state.authToken} subject = {this.state.currentSubject} />
从那里我使用 componentDidUpdate() 方法来处理这个变化:
componentDidUpdate() {
if (this.props.subject) {
axios.get(`http://localhost:3000/api/subjects/${this.props.subject}/sections?access_token=${this.props.authToken}`)
.then(response => {
this.setState({
sections: response.data
})
}).catch(err => {
console.log(err)
})
}
}
一切都按预期工作,但是当我通过 Subjects 组件设置 currentSubject 后尝试在 Sections 组件中 console.log 时,console.log 执行无数次(我猜是 get 请求...... ) 这不是很好,是吗?而且我无法理解为什么会发生这种情况..
【问题讨论】:
-
通读这个问题可能会对您有所帮助:stackoverflow.com/questions/30528348/…。在您的代码中,似乎在每个
componentDidUpdate上都调用了setState,这会导致无限循环。您使用componentDidUpdate有什么原因吗?
标签: reactjs