我们如何在不删除状态字段的情况下进行更新?
async componentDidMount() {
let { get_financial_assessment } = await DAO.getFinancialAssessment()
if( get_financial_assessment ) {
this.setState(get_financial_assessment); <- something with prevState...
} else {
// To-Do: Show the error page.
console.log('You must login to see this page');
}
}
这里是状态
state = {
income_source: '',
employment_status: '',
employment_industry: '',
occupation: '',
source_of_wealth: '',
education_level: '',
net_income: '',
estimated_worth: '',
account_turnover: '',
}
如果我们将 get_financial_assessment
获取为 {}
,则状态当前将更新为 {}
。 :(
我们怎样才能防止这种情况发生?
更新示例输入
{
account_turnover: "$25,000 - $50,000",
cfd_score: 0, <- see this is extra field and this is unintentionally added to our state.
education_level: "Secondary",
employment_industry: ...
...
}
在setState
之后,state
将保留我在state
中指定的相同字段,并更新每个相应字段的值。
问题
- 有时 json 数据没有必填字段,请在
state
中删除该字段。 - 有一个额外的字段,它正在被添加到我们的
状态
最佳答案
从问题来看,可能有2种情况
<强>1。所有值为 '' 的对象
要检查所有键都为 '' 的对象,您必须将代码更新为以下内容
if( get_financial_assessment && Object.values(get_financial_assessment).every(v => v !== '')) {
this.setState(get_financial_assessment);
} else {
// To-Do: Show the error page.
console.log('You must login to see this page');
}
<强>2。空对象(无键)
空对象 {}
的计算结果不会为 false,因此您必须更新 if 语句来检查空对象,如下所示
if( get_financial_assessment && Object.keys(get_financial_assessment).length) {
this.setState(get_financial_assessment);
} else {
// To-Do: Show the error page.
console.log('You must login to see this page');
}
编辑
您可以预先准备好对象,然后使用setState
函数进行设置。
// original state
let state = {account_turnover: "$25,000 - $50,000",cfd_score: 0};
// Response with updated, missing and additional keys
let data = {cfd_score: 3,education_level: "Secondary",employment_industry: ""};
// Update the current state object and set using setState
Object.entries(state).forEach(([k,v]) => state[k] = data[k] ? data[k] : v);
console.log(state);
关于javascript - 我们如何在不删除状态字段的情况下进行更新? (在 React/JavaScript 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50829320/