react:无法在现有状态转换错误期间更新

IT技术 javascript reactjs
2021-05-10 09:10:19

我有一个为我生成时间列表的函数。当它开始呈现时,应该调用该方法并显示状态。它被显示出来,但控制台抛出了多个错误:

setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

我的代码如下所示:

import React, { Component } from 'react';


export default class Timeline extends Component {
    constructor(props) {
        super(); 
            this.state = {
                timeList: 'aa'
            };
        }


      generateTimelineArray(start = 1499162400, end = 1499248800, step = 60) {
      let arr =[];
      for(let i = start; i <= end;i+=step) {
        const date = new Date(i);
        const hours = date.getHours();
        const mins = date.getMinutes();
        arr[i] = {
          time: hours + ":" + mins,
          hour: hours,
          minutes: mins
        };
      } 
    this.setState({ timeList: 'bb'});
        this.setState({ timeList: 'bb'});

    }


  render() {


{this.generateTimelineArray()}
    return (
      <div className="App" >
       {this.state.timeList}
      </div>
    ); 
  }
}

generateTimelineArray 循环遍历指定的参数并创建一个数组。后来我想映射到另一个组件,例如,我将其更改为字符串。

错误的原因是什么,应该如何解决?

1个回答

你不能this.setState在一个render周期调用,就像错误告诉你的那样。为什么不改为generateTimelineArray提供componentWillReceiveProps生命周期中调用或者也许在函数期间,如果您没有看到它的状态发生变化。functionReactcomponentWillMount

这是对状态变化“做出react”的更好地方,因此构建新的组件状态。最终你会陷入一个永无止境的循环,因为你会不断地渲染和重置组件状态

关于 React 生命周期的 Facebook 文档 - componentWillReceiveProps