在react ComponentDidMount中访问this.props [英] Accessing this.props in react ComponentDidMount

查看:352
本文介绍了在react ComponentDidMount中访问this.props的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的反应者,我被困在某个项目上.问题是我从父组件收到了this.props中的api_url.在这个子组件中,我想使用api_url通过JSON获取一些数据.

I am new to react and i am stuck on a certain project. The thing is that I have an api_url in this.props received from a parent component. And in this child component I want to use api_url to fetch some data using JSON.

在父组件中,我有:

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

在子组件中,我想要类似的东西:

and in the child component, I want something like:

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.

so what I need is the corresponding api_url in the url section of $.getJSON.

componentDidMount中是否可以访问this.props,或者是否有其他方法可以实现相同的结果?

Is there a way to access this.props in componentDidMount or is there some other way to achieve the same results?

与此有关的另一件事是,我还在父组件的ComponentDidMount中使用了$.getJSON调用.

Another thing regarding this, is that I'm also using a $.getJSON call in the ComponentDidMount of the parent component.

在此先感谢

推荐答案

在您的类中实现构造函数:

In your class implement the constructor:

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

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

这个反应版本可能更容易获得它.

Probably at this react version is more easy to get it.

这篇关于在react ComponentDidMount中访问this.props的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆