首页  >  问答  >  正文

探索Redux Store切片中修改数组值的方法

<p>我有一个Slice来存储位置信息。我声明了两个函数,set和setLocation。set函数接受一个位置数组,setLocation函数应该设置一个位置。</p> <p>这是存储在locations变量中的示例数据:</p> <pre class="brush:php;toolbar:false;">const locations = [{name: '1', index: 0}, {name: '2', index: 1}];</pre> <p>这是我的slice代码:</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>set(locations)的调用是有效的。但是当location是locations数组中的一个值时,我无法使用setLocation(location)来替换位置数组中的单个位置。 当我在setLocation()函数中使用console.log(state.location)时,我得到了一些代理对象。</p>
P粉197639753P粉197639753388 天前379

全部回复(1)我来回复

  • P粉248602298

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

    你在setLocation操作中得到Proxy的问题是因为在搜索特定位置时,你传递了location.index,但你应该传递location.payload.index

    setLocation: (state, location) => {
       state.locations[location.payload.index] = location
    }

    回复
    0
  • 取消回复