Does each attribute need a reducer?
P粉124070451
P粉124070451 2023-08-17 14:47:45
0
1
382
<p>I'm following this tutorial to increment a number. </p> <p>It works, but now I want to implement it to about 100 configuration values. Do I need to copy counterSlice.js 100 times or do I need to replace the number with an object with 100 properties? </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 allows us to write "modification" logic in reducers. It doesn't actually change the state because it uses the Immer library, // It detects changes to "draft state" and generates a completely new immutable state based on those changes. // Additionally, these functions do not require a return statement. state.value = 1 }, decrement: (state) => { state.value -= 1 }, incrementByAmount: (state, action) => { state.value = action.payload }, }, }) // Generate action creators for each case reducer function export const { increment, decrement, incrementByAmount } = counterSlice.actions export default counterSlice.reducer</pre> <p><br /></p>
P粉124070451
P粉124070451

reply all(1)
P粉404539732

In some cases it may be wise to explicitly create functions for each status field. But if you do have around 100 status fields, then you need to take a more general approach.

I recommend including a key and value field in the payload of the reducer function.

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

      state[key] = value;
    },
  },
})

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!