javascript - React 组件循环更新 (GraphQL)

标签 javascript reactjs ecmascript-6 graphql

美好的一天! 我不断得到

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

这看起来很明显,但我看不到组件中的循环。

ComponentWillUpdate() 显示它在短时间内使用相同的 props 和状态调用大量重新渲染。

提前致谢。

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 时,它​​会再次调用您的渲染。因此,如果您从渲染中调用 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 方法更新

关于javascript - React 组件循环更新 (GraphQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47977038/

相关文章:

javascript - 解构给出解析错误

javascript - 将数组对象展平为单个对象 - Javascript

javascript - 如何隐藏没有产品reactjs的字符

reactjs - React-sizeme 不测量组件的高度

javascript - 如何让多个球在点击时掉落?

javascript - 表单验证不起作用

javascript - 在作为字符串传递的 img src 上 react 传递导入名称作为 Prop

javascript - chrome/chromium 44 中的解构语句未被识别

javascript - AngularJS http promise 触发 4 次

javascript - jQuery 时间和日期