简体   繁体   English

反应 - 检查道具是否存在

[英]React - Check If Props Exist

I searched around the internet for an answer to this question, and I didn't find one. 我在互联网上搜索了这个问题的答案,但我没找到。 Therefore I am posting my question here. 所以我在这里发帖子。

I have a parent component (App) and a child component (Child). 我有一个父组件(App)和一个子组件(Child)。 The App component has a state with some data in it, like so: App组件的状态包含一些数据,如下所示:

class App extends Component {
    constructor() {
        super()

        this.state = {
            currentOrganization: {
                name: 'name',
                email: 'email'
            }
        }
        render() {
            return (
                <Child data={this.state.currentOrganization} />
            )
        }
    }
}

In my Child component, I have a form: 在我的Child组件中,我有一个表单:

class Child extends Component {
    constructor() {
        super()

        this.state = {
            formData: {
                name: '',
                email: '',
            }
        }
    }

        render() {
            return (
            <Form ... />
          )
        }
    }

According to the React docs, forms generally should have a state containing properties that correspond with each element of the form. 根据React文档,表单通常应该具有包含与表单的每个元素相对应的属性的状态。 The form that lies in my Child component must have the data of the currentOrganization (as seen in the App component) pre-populate into itself. 我的Child组件中的表单必须具有currentOrganization的数据(如App组件中所示)预先填充到自身中。

In order to accomplish this, I have to set the state of the Child to the props it receives from its parent. 为了实现这一点,我必须将Child的状态设置为从其父级接收的道具。

What's the best way to check if my Child component received the props it needs in order to update its own state? 检查我的Child组件是否收到了更新自己状态所需的道具的最佳方法是什么?

You can assign default props to component. 您可以将默认道具分配给组件。

class Child extends Component {
  constructor(props) {
    super(props);

    this.state = {
      formData: {
        name: props.name,
        email: props.email,
      }
    }
  }

  render() {
    return (
      <Form ... />
    )
  }
}

Child.defaultProps = {
  name: '',
  email: '',
};

PS props is JS object so You can check property like this "prop_name" in this.props // true|false PS props是JS对象所以你可以"prop_name" in this.props // true|false检查这个"prop_name" in this.props // true|false属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM