javascript - 如何在 React 的构造函数中处理 Null Props

标签 javascript reactjs ecmascript-6

我有一个表单,所以一个典型的表单将有编辑和创建,我对创建没有问题,现有数据是从主容器传递的,每个组件通过 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/

相关文章:

javascript - 单击自定义编辑按钮可进行 X-editable 切换编辑

javascript - 在 React 中改变状态

javascript - 是否可以解构到现有对象上? (JavaScript ES6)

c# - 如何向下滚动到多行 TextBox 的底线,Javascript 的 scrollIntoView 对此不起作用

javascript - 在 Ajax 请求开始和完成时显示和隐藏元素(状态栏)

javascript - 带有 setState 的 React 滚动动画不稳定

javascript - ReactJs:从数组创建组件会导致旧 Prop

javascript - 如何将发出的事件事件绑定(bind)到 redux-saga 中?

javascript - 当我们移动到 Angular 6 中的另一个组件时,如何销毁一个组件?

javascript - 单 View 页面永久链接为空,带有 Iron Router