首頁  >  問答  >  主體

探索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 天前380

全部回覆(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
  • 取消回覆