我有一个具有名为Report
的状态属性的react组件。它符合以下界面:
interface Report {
firstname: string;
lastname: string;
otherinfo: info[];
}
interface info {
dob: string;
gender: string;
email: string;
}
如果我想更新setState
的值,我想知道执行email
的首选方式。
答案 0 :(得分:0)
我相信这样的事情应该有用。
const targetIndex = 0; // assuming this is the index of the element you want to update
const newEmail = 'email@example.com'; // new email address to be set
this.setState(prevState => ({
...prevState,
report: {
...prevState.report,
otherinfo: prevState.report.otherinfo.reduce((accum: info[], currrent: info, currentIndex: number) => {
if (currentIndex === targetIndex) { // this is where we're trying to find the element with the matching index
return [
...accum,
{
...current,
email: newEmail, // this is where we set the new email
}
]
}
return [...accum, current];
}, [])
}
}));
答案 1 :(得分:0)
我想知道您是否可以将Immutability-helper用于您的用例?有点像:
const newReport = update(report, { otherinfo: { email: { $set: newEmail }}});
this.setState({report: newReport})