Javascript 如何在React';s构造函数
我有一个表单,所以一个典型的表单将有编辑和创建,我对创建没有问题,现有的数据是从主容器传递的,每个组件通过道具将其分配给它们自己的状态,就像这样Javascript 如何在React';s构造函数,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个表单,所以一个典型的表单将有编辑和创建,我对创建没有问题,现有的数据是从主容器传递的,每个组件通过道具将其分配给它们自己的状态,就像这样 export default class Name extends Component { constructor(props){ super(props) const { data } = props this.state = { name: data.name } } ... ...
export default class Name extends Component {
constructor(props){
super(props)
const { data } = props
this.state = {
name: data.name
}
}
...
...
}
无论我在创建方面有什么问题,如果在没有数据道具的情况下渲染
,上面的代码都会出错。如何解决这个问题?我能行
this.state = {
name: data && data.name
}
但是假设我有其他字段,这不是一个优雅的解决方案。或者您可以使用defaultProps将props值设置为默认值:
export default class Name extends Component {
static defaultProps = {
name: "name default value",
email: "email default value"
};
constructor(props) {
super(props);
this.state = {
name: this.props.name,
email: this.props.email,
// some other variables
};
}
...... ..........
...... ..........
}
或
您可以在componentWillReceiveProps()方法中更新您的道具值,每次您的道具值从服务器或其他地方更改时,都将执行此方法。详情如下:
componentWillReceiveProps(nextProps) {
if (!this.props.name && nextProps.name) {
// here you can do according to your need
// you can update the values of variables in state here
this.setState({ name: nextProps.name });
}
}
使用默认道具?请检查下面的答案,希望它能帮助你澄清这个概念