以下是我的减速机初始状态:
const InitialState = {
data:[],
SelectUser : null,
name: "Not Yet Selected"
};
下面是从api中获取的我的data []状态:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
}
]
我想将名称从状态为 data [] 的对象更改为状态 name 。其中,对象的id与 SelecUser 状态的对象中的id相同。 SelectUser 也是对象,其内容与 data [] 中的元素相同。所有状态都已设置。
以下是迄今为止创建的减速器:
const InitialState = {
data:[],
SelectUser : null,
name: "Not Yet Selected"
};
export default (state=InitialState, action)=>{
switch(action.type){
case 'FETCH_USER':
return {...state,data:action.payload};
case 'USER_SELECTED':
return {...state,SelectUser:action.payload};
case 'USER_CHANGE':
return {...state,name:action.payload};
default:
return state;
}
};
所有提到的情况以前都已执行。
答案 0 :(得分:1)
我想将名称从状态数据[]中的对象更改为状态名称 具有相同ID的对象(已存储在SelectUser中)
我假设您要更改name
的{{1}}上端,为简单起见,我将其称为action
。
CHANGE_NAME
现在,您只需要在数据中找到对应对象case 'CHANGE_NAME' return handleNameChange(state, action)
是原始内容并覆盖spread
name
答案 1 :(得分:0)
尝试一下
export default (state=InitialState, action)=>{
switch(action.type){
case 'FETCH_USER':
return {...state,data:action.payload};
case 'USER_SELECTED':
return {...state,SelectUser:action.payload};
case 'USER_CHANGE':
return {
...state,
name: state.data.reduce((prev, item)=>{
if(state.SelectUser && state.SelectUser.some(elt=>elt.id === item.id)){
return item.name;
}else{
return prev;
}
}, null);
};
default:
return state;
}
};