Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs `React的.props`inside`getDefaultProps()`?_Reactjs - Fatal编程技术网

Reactjs `React的.props`inside`getDefaultProps()`?

Reactjs `React的.props`inside`getDefaultProps()`?,reactjs,Reactjs,我试图添加一个道具,它依赖于其他道具,这些道具基本上是由组件的所有者组件传递的 所以我做了: propTypes: { user: React.PropTypes.object, comment: React.PropTypes.object }, getDefaultProps: function() { return { admire: new Admire({ user: this.props.user, co

我试图添加一个道具,它依赖于其他道具,这些道具基本上是由组件的所有者组件传递的

所以我做了:

propTypes: {
  user: React.PropTypes.object,
  comment: React.PropTypes.object
},

getDefaultProps: function() {
  return {
    admire: new Admire({
              user: this.props.user, 
              comment:this.props.comment
            })
  };
}
但是,似乎在
getDefaultProps
调用时无法访问props
user
comment


有没有办法定义一个依赖于从所有者组件传递的其他道具的默认道具?

你不应该真的这样修改道具,我敢肯定你会收到控制台警告

您可能希望通过
getInitialState
函数将
approve
存储到状态中

例如

在创建任何实例之前调用,因此不能依赖
this.props
。这是为了得到默认的道具,以防所有者没有通过它们

另一种解决方案是使用
getInitialState
,因为这样可以访问
this.props.user
this.props.comment

propTypes: {
    user: React.PropTypes.object,
    comment: React.PropTypes.object
},
getInitialState: function() {
    return {
        admire: new Admire({
            user: this.props.user,
            comment: this.props.comment
        });
    };
}