探索Redux Store切片中修改数组值的方法
P粉197639753
P粉197639753 2023-08-30 11:35:40
[React讨论组]
<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) =&gt; { state.locations = locations.payload }, setLocation: (state, location) =&gt; { 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粉197639753
P粉197639753

全部回复(1)
P粉248602298

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

setLocation: (state, location) => {
   state.locations[location.payload.index] = location
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号