2016-11-11 83 views
6

大家好,我是新来的反应,我被困在某个项目上。事情是,我有一个api_urlin this.props从父组件收到。在这个子组件中,我想使用api_url来使用JSON获取一些数据。在反应中访问this.props ComponentDidMount

在父组件我有

Repositories api_url={this.state.objs.repos_url} 

和子组件,我想是这样

componentDidMount() { 

    $.getJSON(this.props.api_url, function(json) { 
     for (var i = 0; i < json.length; i++) { 
      var each_repo = json[i] 
      console.log(each_repo["name"]); 
     } 

    }); 
} 

所以我需要的是在$ .getJSON的URL部分相应api_url 。

有没有办法在componentDidMount中访问this.props还是有一些其他方法来实现相同的结果吗?

另一件关于这个问题的是,我还在父组件的ComponentDidMount中使用$ .getJSON调用。 提前致谢。

+2

我不确定完全明白... this.props在整个课程中都可用。所以你的代码是OK的。 –

+0

你已经可以,你的意思是'$ .getJSON'吗?.. –

+0

你的代码工程 - http://jsbin.com/wirodemulu/edit?html,js,console,output - 如果你想访问'this'从'$ .getJSON'中的回调函数中,您需要使用'.bind()'。 –

回答

1

为了获得道具的子组件,您需要创建在子组件的构造函数,然后通过道具来超()函数的属性作为

constructor(props) { 
    super(props); 
    this.state = {} 
} 
componentDidMount(){ 

    $.getJSON(this.props.api_url , function(json) { 
     for (var i = 0; i < json.length; i++) { 
      var each_repo = json[i] 
     console.log(each_repo["name"]); 

     } 

    }); 

    } 

一旦你这样做,你可以访问道具在你的整个孩子组件

+1

我已经尝试过相同的事情,并且当我将this.props.api_url记录到控制台时它返回undefined –

+0

检查父组件中是否存在this.state.objs.repos_url值 –

-1

你有没有尝试将this.componentDidMount = this.componentDidMount.bind(this);添加到你的构造函数?通过这种方式,您可以从componentDidMount到达this

+0

不是必需的。 ComponentDidMount是一个反应生命周期函数,因此已经与上下文绑定。自定义函数需要bind() –

+0

感谢您纠正我! –

1

你可能在你的ajax调用中有this问题。我的猜测是你必须在你的存储库中绑定this,以便你的ajax调用中的this实例指向存储库而不是ajax对象。

0

在你的类实现构造函数:

constructor(props){ 
    super(props); 
    this.state = { 
    //states 
    }; 
} 

componentDidMount(){ 
    //Get this.props 
    console.log(this.props.nameOfProp); 
}; 

可能是在这个反应版本更容易得到它。

+0

这使我发生错误,但如果我在调用this.props.nameOfProp内部渲染它的作品。 –