首頁  >  問答  >  主體

每個屬性都需要一個reducer嗎?

<p>我正在跟隨這個教學來遞增一個數字。 </p> <p>它是有效的,但是現在我想要將其實現到大約100個配置值上。我需要複製counterSlice.js 100次還是需要用一個具有100個屬性的物件替換數字? </p> <p>counterSlice.js</p> <pre class="brush:php;toolbar:false;">export const counterSlice = createSlice({ name: 'counter', initialState: { value: 0, }, reducers: { increment: (state) => { // Redux Toolkit 允許我們在 reducer 中編寫「修改」邏輯。它實際上不會改變狀態,因為它使用 Immer 庫, // 它偵測到對「draft state」的更改,並基於這些變更產生一個全新的不可變狀態。 // 此外,這些函數不需要傳回語句。 state.value = 1 }, decrement: (state) => { state.value -= 1 }, incrementByAmount: (state, action) => { state.value = action.payload }, }, }) // 為每個 case reducer 函數產生 action creators export const { increment, decrement, incrementByAmount } = counterSlice.actions export default counterSlice.reducer</pre> <p><br /></p>
P粉124070451P粉124070451401 天前387

全部回覆(1)我來回復

  • P粉404539732

    P粉4045397322023-08-18 09:20:48

    在某些情況下,明確為每個狀態欄位建立函數可能是明智的。但是如果你確實有大約100個狀態字段,那麼你需要採用更通用的方法。

    我建議在reducer函數的payload中包含一個keyvalue欄位。

    export const configSlice = createSlice({
      name: 'config',
      initialState: {},
      reducers: {
        setConfigValue: (state, action) => {
          const { key, value } = action.payload;
    
          state[key] = value;
        },
      },
    })

    回覆
    0
  • 取消回覆