2016-11-22 79 views
1

我是Redux的新手,並嘗試使用Immutable.js對象作爲我的商店。在處理從服務器獲取的數據並將其轉換回JSON以發佈到服務器時,我發現自己不可避免地需要將JSON轉換爲Immutable,其中fromJS。無論潛在的性能成本如何,這是否正確?在與服務器通信時將Immutable.js對象轉換爲JSON並將其從JSON轉換爲常見信息

+1

什麼是可能的選擇?如果不是'JSON',你如何通過網絡傳輸JavaScript代碼?什麼是潛在的性能成本?你有沒有測量? – Mjh

回答

0

你說的話聽起來很合理。典型的情況是使用Redux時,您在thunk中間件中執行服務器請求,然後使用從服務器收到的數據發送操作。然後,您可以將數據轉換爲immutablejs並將其添加到您的reducer中的狀態。

短sudo的代碼示例:

// Component somewhere 
state.dispatch(fetchData()); 

// Actions 
function fetchData() { 
    function (dispatch, getState) { 
     // Use something to fetch from server 

     dispatch({ type: 'FETCH_REQUEST' }) 
     return fetch('/path/to/server') 
      .then(function (data) { 
       dispatch({ type: 'FETCH_SUCCESS', data: data }) 
      }) 
    } 
} 

// Reducer 
function reducer(state=Map(), action) { 
    switch(action.type) { 
     case 'FETCH_SUCCESS': 
      // Could also take just a part of the data. 
      // Could also create things like List, Map 
      // for specific parts of the data. 
      return fromJS(action.data) 
     default: 
      return state; 
    } 
} 
+0

真的很有幫助的例子。我希望官方文檔能提供這樣的代碼片斷,因爲它建議Immutable作爲一個不錯的選擇 – mylostlenore

+0

@mylostlenore如果這有幫助,你可以將它指定爲接受的答案。 – kjonsson