簡體   English   中英

如何在ES5 Redux reducer中初始化默認數據?

[英]How to initialize default data in ES5 Redux reducer?

暫時我不能使用ES6 / ES2015而且我堅持使用ES5來編寫Redux減速器。 由於reducer的state參數必須是不可變的,即使它未定義,我想出了以下模式:

function myState( state, action ) {
    if ( typeof state === 'undefined' ) {
        return myState( { value1: 'foo', value2: 'bar' }, action );
    }
    // actual state calculation here
}

有關如何使用ES5確保默認值的任何其他建議或意見?

編輯:經過一些問題和建議:我做遞歸調用的原因是我非常認真地對待“狀態是不可變的”。 因此,即使undefined state參數,我也不會更改參數變量本身。 我把不變性帶到了太遠了嗎?

Redux不會強制您使用默認參數語法。 它只關心當它給你undefined的狀態時,你返回其他東西,以便你的應用程序能夠使用初始狀態樹啟動。

ES6中的這個功能:

function counter(state = 0, action) {
  switch (action.type) {
  case 'INCREMENT':
    return state + 1
  case 'DECREMENT':
    return state + 1
  default:
    return state
  }
}

相當於ES5中的這個功能:

function counter(state, action) {
  if (state === undefined) {
    state = 0
  }

  switch (action.type) {
  case 'INCREMENT':
    return state + 1
  case 'DECREMENT':
    return state + 1
  default:
    return state
  }
}

驗證這一點的一個好方法是通過Babel REPL運行此代碼


我做遞歸調用的原因是我非常認真地對待“狀態是不可變的”。 因此,即使未定義state參數,我也不會更改參數變量本身。

這里不需要遞歸調用。 我認為你的問題可能包含一些關於突變和參考分配之間差異的混淆

當你寫作

var x = { lol: true }
x.lol = false

你正在改變 x對象。 這是Redux不允許的。

但是當你寫作

var x = { lol: true }
x = { lol: false }

原始對象保持不變。 x “綁定”(也稱為“變量”)只是開始指向不同的對象。

Redux並不關心你是否改變了state參數所指的內容。 它是您的功能的本地。 無論您是否返回, 只要您不改變實際對象或其中的任何對象 ,就更改引用。

只是更改變量引用的內容不會改變對象:

// good: local variable called "state" refers to a different number
state = state + 1

// good: local variable called "state" refers to a different array
state = state.concat([42])

// good: local variable called "state" refers to a different string
state = state + ", lol"

然而,改變對象本身內部或者鏈接到的對象 (無論是否深層次)都是一種變異,Redux不允許這樣做:

// bad: object that local variable "state" refers to has been mutated
state.counter = state.counter + 1

// bad: object that local variable "state" refers to has been mutated
var sameObjectAsState = state
state.counter = state.counter + 1

// bad: array that local variable "state" refers to has been mutated
state.push(42)

// bad: array that local variable "state" refers to has been mutated
var sameArrayAsState = state
sameArrayAsState.push(42)

// bad: object that is linked from the object that local variable "state" refers to has been mutated
state.something.deep.counter = 42

// bad: object that is linked from the object that local variable "state" refers to has been mutated
var somethingDeep = state.something.deep
somethingDeep.counter = 42

另一種選擇是這樣的:

var initialState = { value1: 'foo', value2: 'bar' };
function myState( state, action ) {
  state = state || initialState;
  // actual state calculation here
}

暫無
暫無

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

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