我有一个为我生成Timeslist的函数。当它开始渲染时,应调用该方法并显示状态。它会显示,但控制台会抛出多个错误:
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通过指定的参数循环并创建一个数组。我后来想要映射到另一个组件,例如目的我将其更改为字符串。
错误的原因是什么以及如何解决?
答案 0 :(得分:2)
您无法在this.setState
周期内拨打render
,就像错误告诉您的那样。为什么不调用generateTimelineArray
提供的componentWillReceiveProps
生命周期function
中的React
?或者也许在componentWillMount
函数期间,如果您没有看到它的状态发生变化。
这是对状态变化做出“反应”的更好地方,因此构建新的组件状态。最终,您将最终处于一个永无止境的循环中,因为您将不断渲染和重置组件状态
Facebook Documentation on React Lifecycle - componentWillReceiveProps