如何在不删除状态的情况下更新? (在React / JavaScript中)

时间:2018-06-13 04:57:10

标签: javascript reactjs

如何在不删除状态字段的情况下进行更新?

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中指定的相同字段,并更新每个相应字段的值。

问题

  1. 有时json数据没有必填字段,请删除state中的字段。
  2. 有一个额外字段,它已添加到我们的state

1 个答案:

答案 0 :(得分:1)

从问题中可以有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);