我试图在关键date
下的我的组件状态的数组中添加渲染日期,但它总是返回0.
constructor(props) {
super(props);
this.state = {
dates: []
}
}
componentWillMount() {
this.renderDateComp()
}
renderDateComp() {
for(var i = 0; i < 5; i++) {
var dat = new Date(Date().valueOf());
dat.setDate(dat.getDate() + i);
this.setState({ dates: this.state.dates.concat(dat) });
console.log(this.state.dates); //prints length of 0
}
}
答案 0 :(得分:6)
首先,状态转换不是立即的,它们是异步的(在大多数情况下)。可以想象每次设置状态时,它会将状态更改添加到更改队列中,并且React会持续处理该队列,执行所有这些状态更改。因此,如果您更改状态,然后在下一行代码上立即打印状态,状态可能无法更改,因为在状态更改添加到列表后,控制台日志立即发生,但是在更改之前实际上已经经历了那个队列。
其次,在for循环后设置状态可能更好,所以你只需要设置一次,而不是5次。
答案 1 :(得分:2)
值得阅读setState()的文档。 https://facebook.github.io/react/docs/react-component.html#setstate
它将对更改进行排队,但如果您想以某种方式使用新值,则会有一个回调版本。
this.setState((prevState, props) => {
return {myInteger: prevState.myInteger + props.step};
});
答案 2 :(得分:2)
建议的方法是:
setState
阵列后,只需拨打dates
。this.state.dates
的回调中记录setState
(仅在React正确更新this.state
后才会调用。这里要注意的关键点是setState
是异步的。您可能不需要在实际代码中console.log
数组。
详细了解setState
here。
constructor(props) {
super(props);
this.state = {
dates: []
}
}
componentWillMount() {
this.renderDateComp()
}
renderDateComp() {
var dates = this.state.dates;
for (var i = 0; i < 5; i++) {
var dat = new Date(Date().valueOf());
dat.setDate(dat.getDate() + i);
dates = dates.concat(dat);
}
this.setState({
dates
}, () => {
console.log(this.state.dates); //prints length of 5
});
}
答案 3 :(得分:1)
更具体地说,如果你这样做:
var subarray= [];
$("input[name='subjects[]']").each(function() {
subarray.push($(this).val());
});
你会得到你期望的结果。