我如何用React Hook useState更新2个对象



我的第一个对象

const [message, setMessage] = useState({ 
Features: {Active:false},
General: {FileTimeout:0,ZipDepth:0}
});

如何更新这个对象?

const handleInput=e=>{
const name=e.currentTarget.name;
const value=e.currentTarget.value;
var temp = {...message}

if(name == 'active'){
if(value==='on'){
temp.Features.Active=true;
}
else{}
} 
else if(name == 'timeout'){
temp.General.ZipDepth= 5;
} 
else if(name == 'zipdepth'){
temp.General.FileTimeout= 7;
}
}
New Values= { Features :{Active:true}, General: {FileTimeout:7,ZipDepth:5}});

我如何像这样更新值?如果有相应的库,我也可以使用。

您正在改变状态对象。即使您创建了message状态的副本temp,您也在改变嵌套属性。你还需要浅层复制所有你正在更新的嵌套状态。

我建议使用功能状态更新来访问以前的消息state, and use a开关statement to cover the different cases on the名称的值,为每个返回下一个状态值。请注意,每一层嵌套状态在更新之前都会被浅拷贝。

const [message, setMessage] = useState({ 
Features: { Active: false },
General: { FileTimeout: 0, ZipDepth: 0 }
});
const handleInput=e=>{
const { name, value } = e.currentTarget;
setMessage(message => {
switch(name) {
case 'active':
if (value === 'on') {
return {
...message, // shallow copy of state
Features: {
...message.Features, // shallow copy nested state
Active: true,
},
};
} else {
// ? return some new state
}
case 'timeout':
return {
...message, // shallow copy of state
General: {
...message.General, // shallow copy nested state
ZipDepth: 5,
},
};
case 'zipdepth':
return {
...message, // shallow copy of state
General: {
...message.General, // shallow copy nested state
FileTimeout: 7,
},
};
default:
return message; // no update, return current state
};
});
}
const [message, setMessage] = useState({ 
Features: {Active:false},
General: {FileTimeout:0,ZipDepth:0}
});
const handleInput=e=>{
const name=e.currentTarget.name;
const value=e.currentTarget.value;
var temp = {...message}

if(name == 'active'){
if(value==='on'){
temp.Features.Active=true;
}
else{}
} 
else if(name == 'timeout'){
temp.General.ZipDepth= 5;
} 
else if(name == 'zipdepth'){
temp.General.FileTimeout= 7;
}
setMessage({...temp})  // You need to call setMessage function in order to update the state.
}

最新更新