React组件循环更新(GraphQL)

时间:2017-12-26 10:15:47

标签: javascript reactjs ecmascript-6 graphql

美好的一天! 我一直在

  

超出最大更新深度。当组件在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}
        />;
    }
}

3 个答案:

答案 0 :(得分:2)

循环是由渲染函数中的this.setState({'items': titlesToRender})引起的

答案 1 :(得分:2)

当您调用this.setState时,它会再次调用render。因此,如果从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方法更新

答案 2 :(得分:1)

你不应该在render中调用setState,在另一个生命周期方法中执行,比如componentDidMount或componentWillReceiveProps:

渲染不应修改状态:https://reactjs.org/docs/react-component.html#render

相关问题