reactjs - Redux reducer - modifying array with forEach
问题描述
Have a small problem with fetching and based on response updating an array inside my state in Redux.
First I have done the whole array update with forEach in actions (based on my initial state object) and sent it ready to reducer, it worked. Simple.
But then read tutorials that modifying should be done only in the reducer, and that action should only deal with getting the response. So I have tried doing it this way, two ways, both failed.
The payload i have dispatched to reducer in both cases was just the ready response i have got.
Can someone please enlighten me what went wrong and what's the correct way to do this in reducer?
Both approaches didn't work:
export const handleMusicCards = (state = musicState, action = {}) => { switch (action.type) {
case REQUEST_MUSIC_SUCCESS:
return Object.assign({}, state, {
musicStateItemList: state.musicStateItemList
.forEach((el, i) => {
el.track = action.payload.message.body.track_list[i].track.track_name;
el.album = action.payload.body.track_list[i].track.album_name;
el.artist = action.payload.body.track_list[i].track.artist_name;
el.id = action.payload.body.track_list[i].track.track_id;
el.favClicked = false;
el.addedToFav = false;
}),
isLoading: false
});
} }
export const handleMusicCards = (state = musicState, action = {}) => { switch (action.type) {
case REQUEST_MUSIC_SUCCESS:
return Object.assign({}, state, {
musicStateItemList: state.musicStateItemList
.forEach((el, i) => {
return {
...el,
track: action.payload.message.body.track_list[i].track.track_name,
album: action.payload.message.body.track_list[i].track.album_name,
artist: action.payload.message.body.track_list[i].track.artist_name,
id: action.payload.message.body.track_list[i].track.track_id,
favClicked: false,
addedToFav: false,
}
}),
isLoading: false
});
} }
解决方案
I am not sure after reading it where the failure is occurring. A little more about redux conventions.
The action objects are only to describe what changes should be made to the state. The reducer is where the state should actually be changed. In redux, you never want to modify the state object, instead you want to copy it and return a new object with the changes, as described by the action objects.
So you might have a reducer case that looks something like this...
const reducer = (state, action) => {
switch (action.type) {
case NEW_RECORD_SUBMIT :
return {
...state,
newRecordStatus: action.status,
};
default :
return state;
}
};
推荐阅读
- c# - 在 C# 中使用套接字
- c# - 从 4 个球体中获取 X、Y、Z 位置
- facebook-graph-api - 使用 Facebook Instagram API business_discovery 获取特定媒体的 like_count 和 comments_count
- python - 具有固定域的整数非线性优化(重新编辑)
- sql-server - 用于备份数据库的 sql server SSMS 与 ODBC 的不同行为
- caching - 如何在没有构造函数的 Asp.Net core 2 中使用内存缓存
- javascript - 在 bot 框架中使用自适应卡登录
- javascript - 作为客户端用户将导出到 csv 选项添加到 Highcharts 图表?
- amazon-web-services - AWS 代码部署。AppSpec:指定位置的脚本:scripts/start_server.sh 不可执行
- android - Android Wear 授权不起作用