我遇到错误:
已超过最大更新深度。当一个组件发生这种情况 重复调用componentWillUpdate内的setState或 componentDidUpdate。 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
});
}
}
答案 0 :(得分:1)
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
});
}
}
}
答案 1 :(得分:1)
正在发生的事情:
this.state.searchValue
变为真实,它就会在CDM中更新状态您应该怎么做:
componentDidUpdate(prevProps, prevState)
if(this.state.searchValue !== "" && this.state.searchValue !== prevState.searchValue) {...}
答案 2 :(得分:1)
如果在主状态调用之前两个状态相等,则可以通过空比较来解决。另外,我对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
});
}
}