我面临一个错误:
超过最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。
守则如下:
componentDidUpdate() {
this._updateLocalStorage();
if (this.state.searchValue !== "") {
this.setState({
filteredNotes: this.state.notes.filter(
note =>
note.text
.toLowerCase()
.indexOf(this.state.searchValue.toLowerCase()) !== -1
)
});
} else {
this.setState({
filteredNotes: this.state.notes
});
}
}
如果在主状态调用之前两个状态相等,则可以通过放置空比较来修复此问题。此外,我还改变了else的状况。
componentDidUpdate(prevProps, prevState) {
this._updateLocalStorage();
if (this.state.searchValue !== "") {
this.setState({
filteredNotes: this.state.notes.filter(
note =>
note.text
.toLowerCase()
.indexOf(this.state.searchValue.toLowerCase()) !== -1
)
});
} else if(prevState.filteredNotes === this.state.filteredNotes) {
//do nothing
} else if(this.state.searchValue === "") {
this.setState({
filteredNotes: this.state.notes
});
}
}
如果状态发生更改,则每次都会调用componentDidUpdate。
因此,您可能需要在内部谨慎使用setState
。
为这些setState
严格设置条件。也许像下面这样:
一些注意事项:
componentDidUpdate(pervProps, prevState) {
if (prevState.filteredNotes !== this.state.filteredNotes) {
this._updateLocalStorage();
if (this.state.searchValue !== "") {
this.setState({
filteredNotes: this.state.notes.filter(
note =>
note.text
.toLowerCase()
.indexOf(this.state.searchValue.toLowerCase()) !== -1
)
});
} else {
this.setState({
filteredNotes: this.state.notes
});
}
}
}
这就是正在发生的事情:
你应该做什么:
组件didUpdate(prevProps,prevState)
if(this.state.searchValue !== "" && this.state.searchValue !== prevState.searchValue) {...}