Javascript React - 检查道具是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46330124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:24:16  来源:igfitidea点击:

React - Check If Props Exist

javascriptreactjs

提问by lsimonetti

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). The App component has a state with some data in it, like so:

我有一个父组件(App)和一个子组件(Child)。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. 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.

根据 React 文档,表单通常应该有一个包含与表单的每个元素对应的属性的状态。位于我的 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 组件是否收到更新其自身状态所需的道具的最佳方法是什么?

回答by Rafael Hovsepyan

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: '',
};

P.S. propsis 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