Explore ways to modify array values in Redux Store slices
P粉197639753
2023-08-30 11:35:40
<p>I have a Slice to store location information. I declared two functions, set and setLocation. The set function accepts an array of locations, and the setLocation function should set a location. </p>
<p>This is sample data stored in the locations variable: </p>
<pre class="brush:php;toolbar:false;">const locations = [{name: '1', index: 0}, {name: '2', index: 1}];</pre> ;
<p>This is my slice code: </p>
<pre class="brush:php;toolbar:false;">import { createSlice } from '@reduxjs/toolkit'
export const locationsSlice = createSlice({
name: 'locations',
initialState: {
locations: null,
},
reducers: {
set: (state, locations) => {
state.locations = locations.payload
},
setLocation: (state, location) => {
state.locations[location.index] = location
}
},
})
export const { set, setLocation } = locationsSlice.actions
export default locationsSlice.reducer</pre>
<p>The call to set(locations) is valid. But when location is a value in the locations array, I cannot use setLocation(location) to replace a single location in the locations array.
When I use console.log(state.location) in setLocation() function, I get some proxy objects. </p>
The problem you are getting
Proxy
in thesetLocation
operation is because when searching for a specific location, you are passinglocation.index
, but you should be passinglocation.payload.index
.