簡體   English   中英

Redux 減速器 state 突變和恢復初始 state

[英]Redux reducer state mutations and restoring initial state

恢復初始 state 的最佳方法是什么? 對於此示例,假設我可以通過調度以下操作來編輯汽車:

dispatch(actions.editModel('Civic'));

dispatch(actions.editType({
    make: 'Ford',
    model: 'Focus'
}));

dispatch(actions.restoreInitialState());

我的減速器看起來像這樣:

const initialState = {
  id: '1',
  vehicle: 'car',
  type: {
    make: 'Honda',
    model: 'Accord'
  },
  license: 'abc'
}

export default createReducer({
  [actions.editType]: (state, payload) => ({
    ...state,
    type: payload // payload is an object
  }),
  [actions.editModel]: (state, payload) => ({
    ...state,
    type: {
      ...state.type,
      model: payload // payload is a string
    }
  }),
  [actions.restoreInitialState]: (state) => ({
    state: initialState // initial state has nested objects
  })
}, initialState)

我是否有風險改變我的 state 或錯誤地恢復我的初始 state? 這可能有點矯枉過正,但我正在考慮像這樣編輯我的減速器:

export default createReducer({
  [actions.editType]: (state, payload) => ({
    ...state,
    type: { 
        ...payload // payload is an object
    }
  }),
  [actions.editModel]: (state, payload) => ({
    ...state,
    type: {
      ...state.type,
      model: payload // payload is a string
    }
  }),
  [actions.restoreInitialState]: (state) => ({
    state: {
        ...initialState // initial state has nested objects
    }
  })
}, initialState)

當我通過有效負載傳遞 object 與僅引用我的初始 state 時有區別嗎? (加上我最初的 state 包含嵌套對象)

你有一個很好的問題。 要回答這個問題,您需要考慮為什么避免在 React 中改變數據如此重要。 在 state 中的每一次更改 - React 都會對更新的虛擬 DOM 與舊的虛擬 DOM 進行淺顯比較。 在這個淺層比較中——當它遇到對象時——它只檢查 object 的地址。 所以——只要你有一個新的父地址——DOM 就會正確更新。

現在,每次你從減速器返回時——只要你返回一個帶有更新的 state 的新 object——返回 {... state} 或一個具有不同地址的 object - 例如。 return initialState - 它是完美的。 您無需擔心突變。 即使您在 state 中有嵌套的 object,也是如此。 只要您更改父級的地址 - DOM 就會正確更新。 因此,請隨意使用您在第一種情況下所做的代碼。 您不需要分布在嵌套對象上。 無論如何,您的有效負載將具有不同的地址。

唯一需要擔心的是做這樣的事情:

    case [actions.editModel]:
        const updatedState = state
        updatedState.model = payload;
        return updatedState;

在這種情況下,state object 通過引用 updatedState 來傳遞 - 這意味着它們將共享相同的地址。 並且由於您要返回 updatedState - 地址沒有更改,並且 DOM 不會正確/一致地更新。

你可以簡單地這樣做:

[actions.restoreInitialState]: () => initialState;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM