undefined道具最佳实践

时间:2017-12-25 14:02:52

标签: reactjs

让我们假设有一个Child组件以这种方式呈现

<Child text="foo" action={this.bar} />

此处textaction是Child组件的两个道具。

但是如果没有提供给Child组件的道具

<Child />

Child组件会引发undefined道具异常this.props.text is undefined或类似事件。

即使在没有提供道具的情况下,呈现Child组件的最佳做法是什么?

我是否必须始终在Child组件中进行检查。

if (this.props.text !== undefined) && (this.props.action !== undefined) 
  //then render

1 个答案:

答案 0 :(得分:0)

最佳做法是使用var database = firebase.database(); var rootRef = database.ref(); rootRef.orderByChild('email') .equalTo('tomcruise@firebasemyapp.com') .on('child_added') .then(function(snapshot){ var result = snapshot.val(); //Do what you want with the result }); 包,例如:

PropTypes

这将在控制台中显示警告消息。

要使用它,您需要安装它:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Person extends Component {
  render () {
    <h1>{this.props.name}</h1>
  }
}

Person.propTyeps = {
  name: PropTypes.string.isRequired
}

您可以找到更多文档here,希望它有所帮助。