2016-05-30 59 views
1

有很多關於數組反應狀態更新的帖子,但是他們都沒有解決我的問題。反應this.setState沒有更新數組狀態變量

我使用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'); 

}, 


}); 
+0

爲什麼要創建兩次日曆?爲什麼要使用es5和es6混合?最重要的是,你可能不應該在這裏使用jquery,還有其他的方式來創建一個日曆,這樣你就不會在反應之外進行大量的dom操作(這是首選的做法) –

+0

你是否有更好的鏈接反應日曆的例子? –

+0

我的意思是做一個簡單的谷歌搜索..找到這樣的結果。 [鏈接1](https://github.com/Hacker0x01/react-datepicker).... [鏈接2](https://github.com/zippyui/react-date-picker).... [一堆不同例子](https://react.rocks/tag/DatePicker)... –

回答

9

原來「的setState」不更新狀態變量,但直到函數執行完畢(即直到你的代碼退出的功能塊我沒有意識到它沒有這樣做。我正在檢查setState語句後的this.state.variable,這使得它看起來像變量沒有更新。

+0

這讓我非常感謝,所以謝謝你這個! – leaksterrr