Does each attribute need a reducer?
P粉124070451
2023-08-17 14:47:45
<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>
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
andvalue
field in the payload of the reducer function.