setState不更新数组状态变量

setState不更新数组状态变量

本文介绍了反应this.setState不更新数组状态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

There are many postings about react state update involving array, but none of them seem to address my case.

我正在使用FullCalendar.io组件,该组件接受父组件中作为道具的一系列事件,并填充日历单元格。我试图基于nextProps.cal_events设置状态'cal_events_state',但是由于某种原因,cal_event_state设置为[](显然初始状态值被覆盖了)。

I'm using the FullCalendar.io component which accepts an array of events as a prop from the parent component, and populates the calendar cells. I tried to setState 'cal_events_state' based on nextProps.cal_events, but for some reason cal_event_state is set to [] (apparently the initial state value is overwritten).

什么是我想念吗?

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'确实更新了状态变量,但直到功能执行完成后我才意识到它不会这样做(即直到您的代码退出功能块。我正在setState语句后立即检查this.state.variable,这使得看起来该变量未更新。

It turned out that 'setState' does update the state variable, but I didn't realize it doesn't do so until the execution of the function is completed (ie. until your code exit the function block. I was checking the this.state.variable right after the setState statement, which made it look like the variable is not updated.

这篇关于反应this.setState不更新数组状态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:27