search

Home  >  Q&A  >  body text

Explore ways to modify array values ​​in Redux Store slices

<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粉197639753P粉197639753453 days ago436

reply all(1)I'll reply

  • P粉248602298

    P粉2486022982023-08-31 09:48:51

    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
    }

    reply
    0
  • Cancelreply