如果存储日期不是当前日期,则显示图片

时间:2016-11-20 21:35:17

标签: reactjs react-native

我有两张照片,每隔一天就要显示一张。 我使用http://momentjs.com/并根据以下代码检查storedDate = currentDate。但是,我发现storeDate的状态没有得到更新。 有人能在这里说清楚吗?

getInitialState() {
  storedDate: ''
}

onDateChanged(currentDate) {
  this.setState({ storedDate: currentDate });
},

render(){
var currentDate = moment();
var displayImage;
if (currentDate.isSame(this.state.storedDate, 'day')) {
  displayImage = Image1;
  this.onDateChanged(currentDate);
} else {
  displayImage = Image2;
}
}

1 个答案:

答案 0 :(得分:1)

渲染函数假设是纯函数,即它不应该改变状态。

每次更改状态时React都会重新渲染,因此渲染函数中的setState会抛出无限循环渲染。

更多信息: https://facebook.github.io/react/docs/react-component.html#render

甚至在使用componentWillMount()生命周期方法

挂载组件之前更新状态

了解更多: https://facebook.github.io/react/docs/react-component.html#componentwillmount

此SO答案可能会提供更多见解:ReactJS - Does render get called any time "setState" is called?