反应this.setState不更新数组状态变量

时间:2016-05-30 21:08:53

标签: arrays reactjs

有许多关于反应状态更新涉及数组的帖子,但它们似乎都没有解决我的问题。

我使用FullCalendar.io组件,该组件接受来自父组件的事件数组,并填充日历单元格。我试着设置State' cal_events_state'基于nextProps.cal_events,但由于某种原因,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');

},


});

1 个答案:

答案 0 :(得分:10)

原来,&#39; setState&#39;更新状态变量,但我没有意识到它没有这样做,直到函数的执行完成(即直到你的代码退出功能块。我正在检查this.state.variable紧跟在setState语句之后,这使得它看起来像变量没有更新。

相关问题