如何简化嵌套的 setState();如何使对象泛型?(状态的不同字段/键太多)



我有嵌套状态,需要通过键的值设置其状态。

state = {
income_source: {
type: 'text', label_name: 'Income Source', value: '', helper: 'dropdown',
},
employment_status: {
type: 'text', label_name: 'Employment Status', value: '', helper: 'dropdown',
},
...

我从get_financial_assessment对象中获得了巨大的列表,当我尝试在 componentDidMount(( 中setState时,代码变得混乱。

async componentDidMount() {
let { get_financial_assessment } = await DAO.getFinancialAssessment()
if( get_financial_assessment ) {
const {
account_turnover,
cfd_score,
education_level,
employment_industry,
employment_status,
estimated_worth,
financial_information_score,
income_source,
net_income,
occupation,
source_of_wealth,
total_score,
trading_score,
} = get_financial_assessment;
this.setState(prevState => ({
anticipated_account_turnover: {...prevState.anticipated_account_turnover, value: account_turnover},
occupation: {...prevState.occupation, value: cfd_score},
level_of_education: {...prevState.level_of_education, value: education_level},
source_of_wealth: {...prevState.source_of_wealth, value: employment_industry},
net_annual_income: {...prevState.net_annual_income, value: employment_status},
estimated_net_worth: {...prevState.estimated_net_worth, value: estimated_worth},
source_of_wealth: {...prevState.source_of_wealth, value: financial_information_score},
}));
} else {
console.log('nope');
}
}

更新1(一种可能的方法可能是,,,一旦我们得到数据,我们就可以创建一个对象并将该对象设置为状态。-> 这可能是最好的答案? 2(任何其他方法???

您可以使用Object.entries()

将它们迭代映射到具有更新value的新对象。

似乎您正在将一些不会通过 API 更新的静态数据保留在状态中,因此更好的方法可能是将它们保存在单独的变量中:

const metaData = {
income_source: {
type: 'text', label_name: 'Income Source', helper: 'dropdown' // no `value` here
},
...
}

然后,您的状态只需要包含实际的动态数据:

state = {
income_source: '',
employment_status: ''
...
}

更新它只是:

this.setState(get_financial_assessment);

您还可以使用对象解构来避免设置不需要的状态:

const { trading_score, unwantedProperty, ...imptData } = get_financial_assessment;
this.setState(imptData);

如果你想有一个更简单的初始状态,你也可以这样做:

state = {
data: {}
}
....
this.setState({ data: get_financial_assessment })
...
// in `render`, provide default value if property is not set
{this.state.data.income_source || ''} 

最新更新