有很多关于涉及数组的 react 状态更新的帖子,但它们似乎都没有解决我的问题。
我正在使用 FullCalendar.io 组件,该组件接受事件数组作为来自父组件的 prop,并填充日历单元格。我尝试基于 nextProps.cal_events 设置状态 'cal_events_state',但由于某种原因 cal_event_state 被设置为 [](显然初始状态值被覆盖)。
我错过了什么?
import React from 'react';
import ReactDOM from 'react-dom';
var $ = require ('jquery')
var Calendar = React.createClass ({
render: function() {
return <div id="calendar"></div>;
},
getInitialState: function() {
return {
cal_events_state: [{"due": "201505", "title": "Production"}]
, test_state: 11
}
},
componentDidMount: function() {
var self = this;
const var_cal_events = this.props.cal_events; //This prop is blank at this point because ajax hasn't returned an array yet.
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: var_cal_events;
})
},
componentWillReceiveProps: function(nextProps) {
var self = this;
var var_cal_events = nextProps.cal_events; // after receiving the ajax fetch payload, this has some event tasks.
this.setState({
cal_events_state: var_cal_events, // This doesn't update state with the newly received payload
test_state: 22 // This updates state
})
$('#calendar').fullCalendar({
events: var_cal_events
})
$('#calendar').fullCalendar('refetchEvents');
},
});
最佳答案
事实证明“setState”确实更新了状态变量,但我没有意识到直到函数执行完成(即直到你的代码退出函数 block )它才这样做。我正在检查this.state.variable 就在 setState 语句之后,这让它看起来像变量没有更新。
关于arrays - react this.setState 不更新数组状态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533692/