在react ComponentDidMount中访问this.props [英] Accessing this.props in react ComponentDidMount
问题描述
我是新来的反应者,我被困在某个项目上.问题是我从父组件收到了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屋!