在 redux reducer 中更改状态的内部键
Change inside key of a state in redux reducer
我有以下减速器:
const ListingReducer = (state={
fetched:false
},action) => {
if ( action.payload )
{
console.log("action.token",action.token);
console.log("action.payload.profiles",action.payload.profiles);
}
switch(action.type)
{
case 'SET_LISTING_DATA':
state = {
...state,
[action.token] : action.payload,
fetched : true
}
break;
case 'APPEND_LISTING_DATA':
// console.log("Previous state was: "state[action.token]);
state[action.token]
= {
...state[action.token],
profiles : [...state[action.token].profiles,...action.payload.profiles],
fetched : true
}
// console.log("Next state is: "+state[action.token]);
break;
}
return state;
}
操作:
- SET_LISTING_DATA:它将数据设置到键
action.token
中,其中有一个名为 profiles
. 的键
- APPEND_LISTING_DATA:它将数据附加到状态的
profile
键中。
我可以在配置文件键中看到添加的配置文件,但它不会更新视图。
配置文件位于:
state[action.token] ={name:y,data:xy,profiles:[id:x,{},{}],...}
看来您需要更改 state[action.token]
但还要保留以前的状态数据,否则您将始终覆盖您的状态。
Changing/mutating 直接声明道具不是一个好习惯。
case 'APPEND_LISTING_DATA':
return {
...state,
[action.token]: {
...state[action.token],
profiles: [
...state[action.token].profiles,
...action.payload.profiles,
],
fetched: true,
}
}
我有以下减速器:
const ListingReducer = (state={
fetched:false
},action) => {
if ( action.payload )
{
console.log("action.token",action.token);
console.log("action.payload.profiles",action.payload.profiles);
}
switch(action.type)
{
case 'SET_LISTING_DATA':
state = {
...state,
[action.token] : action.payload,
fetched : true
}
break;
case 'APPEND_LISTING_DATA':
// console.log("Previous state was: "state[action.token]);
state[action.token]
= {
...state[action.token],
profiles : [...state[action.token].profiles,...action.payload.profiles],
fetched : true
}
// console.log("Next state is: "+state[action.token]);
break;
}
return state;
}
操作:
- SET_LISTING_DATA:它将数据设置到键
action.token
中,其中有一个名为profiles
. 的键
- APPEND_LISTING_DATA:它将数据附加到状态的
profile
键中。
我可以在配置文件键中看到添加的配置文件,但它不会更新视图。
配置文件位于:
state[action.token] ={name:y,data:xy,profiles:[id:x,{},{}],...}
看来您需要更改 state[action.token]
但还要保留以前的状态数据,否则您将始终覆盖您的状态。
Changing/mutating 直接声明道具不是一个好习惯。
case 'APPEND_LISTING_DATA':
return {
...state,
[action.token]: {
...state[action.token],
profiles: [
...state[action.token].profiles,
...action.payload.profiles,
],
fetched: true,
}
}