我有一个表单,所以一个典型的表单将有编辑和创建,我对创建没有问题,现有数据是从主容器传递的,每个组件通过 Prop 获取它并分配给自己的状态,就像这样
export default class Name extends Component {
constructor(props){
super(props)
const { data } = props
this.state = {
name: data.name
}
}
...
...
}
我怎么会遇到创建问题,如果<Name />
,上面的代码就会出错在没有数据 Prop 的情况下呈现。如何解决这个问题?我能行
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() 方法中更新您的 props 值,每当您的 props 值发生变化时,无论是来自服务器还是其他东西,此方法都会执行。如下所示:-
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 });
}
}
关于javascript - 如何在 React 的构造函数中处理 Null Props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48499684/