javascript - 我们如何在不删除状态字段的情况下进行更新?(在反应/JavaScript 中)
问题描述
我们如何在不删除状态字段的情况下进行更新?
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
as {}
,则当前状态将更新为{}
。:(
我们怎样才能防止这种情况发生?
更新样本输入
{
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
. - 有一个额外的字段,它被添加到我们的
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.空对象(无键)
空对象{}
不会评估为假,因此您必须更新 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);
推荐阅读
- vim - 你能在 emacs 的邪恶模式下使用 vim 脚本和插件吗?邪恶模式的限制是什么?
- c - C:将字符串复制到字符串列表中
- javascript - 不使用下拉菜单访问对象,ngFor
- bots - Discord Bot- 使用 YAGPDB bot 的反应投票
- hadoop - 访问 kerberos Hive 的 java 操作(启用 SSL)
- c++ - 为什么这个对 sprintf_s() 的调用有效,我怎样才能在我的计算机上使它工作?
- serverless - 无服务器云原生也是如此吗?
- kubernetes - 从同一 pod 上的另一个容器在容器上运行 python 脚本
- agora.io - Agora 视频直播
- c - 我的 CS50 模糊功能无法正常工作