Explore ways to modify array values ​​in Redux Store slices
P粉197639753
P粉197639753 2023-08-30 11:35:40
0
1
455
<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>
P粉197639753
P粉197639753

reply all(1)
P粉248602298

The problem you are getting Proxy in the setLocation operation is because when searching for a specific location, you are passing location.index, but you should be passing location.payload.index.

setLocation: (state, location) => {
   state.locations[location.payload.index] = location
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template