gpt4 book ai didi

javascript - 减少 Prop 数量

转载 作者:行者123 更新时间:2023-12-01 00:17:46 24 4
gpt4 key购买 nike

我有一个组件,用户可以从中路由到表单。有两种选择:创建新表单或编辑旧表单。我将带有链接位置的所有数据发送到该表单组件。但因为我有超过 8 个字段,所以验证位置状态是否存在或如果不存在位置状态时会变得困惑,请使用默认值。

目前我有类似的东西:

this.state = {
firstName: this.props.location.state !== undefined ?
this.props.location.state.userProfile.firstName : '',
familyName: this.props.location.state !== undefined ?
this.props.location.state.userProfile.familyName : '',
address: this.props.location.state !== undefined ?
this.props.location.state.userProfile.address : 'Enter your address',
city: this.props.location.state !== undefined ?
this.props.location.state.userProfile.city : 'Select your city',
country: this.props.location.state !== undefined ?
this.props.location.state.userProfile.country : 'Select your country',
field: this.props.location.state !== undefined ?
this.props.location.state.userProfile.field : '',
message: this.props.location.state !== undefined ? 'Save my changes' : 'Create'
}

这样收到的:

<Link to={{
pathname: '/register/create', state: {
userProfile: item <--comes from mapping
}
}}>

有没有更好的方法来实现?也许只是将主对象设置为状态,然后在该对象内设置 State 的字段?

也可以选择使用 Context,但据我所知,它不应该仅用于将 Prop 传递给 child ?

最佳答案

我宁愿解构对象并在任何数据的情况下都有一个默认对象

// this could be even outside of your class.
const defaultObj = {
firstName: '',
familyName: '',
address: 'Enter your address',
city: 'Select your city',
country: 'Select your country',
field: '',
}

/* the constructor*/

constructor(){
const { userProfile = {} } = this.props.location.state || {};

this.state = {
...defaultObj
...userProfile
}
}

关于javascript - 减少 Prop 数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59645834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com