【问题标题】:I am unable to set default values for the props in child component in reactjs我无法在 reactjs 中为子组件中的道具设置默认值
【发布时间】:2015-12-23 14:57:47
【问题描述】:

我有一个名为“Component_A”的父组件和一个子组件“Component_B”。我正在尝试从父组件中的服务器获取数据并将其作为道具传递给子组件。但是在我在父“Component_A”的“componentDidMount”函数中进行ajax调用之前,我的道具将没有值。所以我正在尝试使用“getDefaultProps”在子组件“Component_B”中设置 defaultProps。但是好像不行!

var Component_A = React.createClass({
        componentDidMount : function(){
            //Get data from server and set it in state variable called "data"
        },
        render : function(){
            return (
                <ComponentB sampleData={this.state.data} />
            )
        }
    })

    var ComponentB = React.createClass({
        getDefaultProps : function (){
            return {
                data : {
                  vehicle : {
                      make :{
                         name : "Ford"
                      },
                      model : {
                         name : "Focus"
                      }
                  }
                }
            }
        },
        render : function(){
            return (
                 <div> {this.props.data.vehicle.make.name} </div>
            )
        }
    })

当我加载页面时,我得到“Uncaught TypeError: Cannot read property 'make' of undefined”

【问题讨论】:

  • 我知道您没有在这里展示它,但是您是否对组件 A 的初始状态进行了任何操作?
  • @Matt 我的“getInitialState”中只返回了一个空对象。

标签: reactjs


【解决方案1】:
   render : function(){
            <ComponentB sampleData={this.state.data} />
        }

一切正常,也许你忘了return这里

【讨论】:

  • 嗨,对不起。我在这里错过了代码中的 return 语句,但我在实际代码中有 return 语句。我已经更正了上面的代码。
  • 你尝试记录 this.props 吗?
  • 我在渲染函数中试过了。由于某种原因,它是空对象“{}”
【解决方案2】:

把A的渲染改成这个-

render : function(){ 
    if(this.state.data){
        return ( <ComponentB data={this.state.data} /> );
    }
    else{
        return ( <ComponentB />);
    }
 }

【讨论】:

  • 我认为这应该可行,但这是最好的方法吗?我不这么认为!!
  • 这个问题的出现是因为组件 B 不是接收离散的 props,而是将它们全部放在一个大对象中。并且组件 A 为这个对象发送一个空值,覆盖 B 中定义的默认 props。在获取对象 props 时,理想情况下,必须在 componentWillReceiveProps 或渲染中将传入的值与默认值合并。
  • 这是否意味着不鼓励使用复杂的道具?我的意思是有嵌套对象的道具?
  • 不,事实并非如此。大多数组件都支持复合的“样式”。让我们看看 getDefaultProps 是如何工作来理解这里的问题的。 getDefaultProps 函数只被调用一次,并且结果被缓存用于组件的所有实例。当 props 的值为“undefined”时,默认的 props 生效。在您的情况下,A 将值作为“null”发送,这不是未定义的。因此不应用 defaultProps。
  • 啊……现在我明白了……所以我想有两种可能的解决方案!一种是您所说的,另一种可能是保持我的数据简单可能是?而不是嵌套对象,可能是我只发送简单对象吗?像 { makeName : "", modelName: "" } 我说的对吗?
猜你喜欢
  • 2021-11-22
  • 2016-10-26
  • 1970-01-01
  • 2017-11-09
  • 2016-01-30
  • 2014-06-23
  • 1970-01-01
  • 2017-03-27
  • 2019-07-23
相关资源
最近更新 更多