美好的一天!我一直在
超出最大更新深度。当组件在componentWillUpdate或componentDidUpdate中重复调用setState时,可能会发生这种情况。 React限制嵌套更新的数量以防止无限循环。
看起来很明显,但我看不到组件中的循环。
ComponentWillUpdate()显示它在很短的时间内调用大量具有相同道具和状态的重新渲染。
提前致谢。
SRC / TitleList.js
class TitleList extends Component {
constructor(props) {
super(props)
this.state = {'items': null}
}
onSortEnd = ({oldIndex, newIndex}) => {
this.setState({
items: arrayMove(this.state.items, oldIndex, newIndex),
});
};
render() {
if (this.props.allTitlesQuery && this.props.allTitlesQuery.loading){
return <div>Loading</div>
}
if (this.props.allTitlesQuery && this.props.allTitlesQuery.error) {
return <div>Error!</div>
}
const titlesToRender = this.props.allTitlesQuery.allTitles
this.setState({'items': titlesToRender})
return <SortableList
items={this.state.items}
onSortEnd={this.onSortEnd}
/>;
}
}
当你调用this.setState时,它会调用你的render
again。因此,如果从render中调用setState,它将进入递归循环。
你可以尝试一下: -
class TitleList extends Component {
constructor(props) {
super(props)
this.state = {'items': null}
}
componentDidMount () {
this.updateState(props);
}
componentWillReceiveProps (nextProps) {
if (this.props.allTitlesQuery.allTitles !== nextProps.allTitlesQuery.allTitles) {
this.setState(nextProps);
}
}
updateState (props) {
this.setState({"items":props.allTitlesQuery.allTitles});
}
onSortEnd = ({oldIndex, newIndex}) => {
this.setState({
items: arrayMove(this.state.items, oldIndex, newIndex),
});
};
render() {
if (this.props.allTitlesQuery && this.props.allTitlesQuery.loading){
return <div>Loading</div>
}
if (this.props.allTitlesQuery && this.props.allTitlesQuery.error) {
return <div>Error!</div>
}
return <SortableList
items={this.state.items}
onSortEnd={this.onSortEnd}
/>;
}
}
使用componentDidMount
方法首次渲染数据,如果数据更改使用componentWillReceiveProps
方法更新
循环是由渲染函数中的this.setState({'items': titlesToRender})
引起的
你不应该在render中调用setState,在另一个生命周期方法中执行,比如componentDidMount或componentWillReceiveProps:
渲染不应该修改状态:https://reactjs.org/docs/react-component.html#render