Nit*_*hna 17 javascript jquery reactjs
大家好,我是新来的反应,我被困在某个项目上.问题是我有一个api_urlin this.props从父组件收到.在这个子组件中,我想使用api_url使用JSON获取一些数据.
在我有的父组件中
Repositories api_url={this.state.objs.repos_url}
Run Code Online (Sandbox Code Playgroud)
在儿童组件中,我想要类似的东西
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"]);
}
});
}
Run Code Online (Sandbox Code Playgroud)
所以我需要的是$ .getJSON的url部分中相应的api_url.
有没有办法在componentDidMount中访问this.props,还是有其他方法可以实现相同的结果?
另一件事是我也在父组件的ComponentDidMount中使用$ .getJSON调用.提前谢谢.
在您的类中实现构造函数:
constructor(props){
super(props);
this.state = {
//states
};
}
componentDidMount(){
//Get this.props
console.log(this.props.nameOfProp);
};
Run Code Online (Sandbox Code Playgroud)
在此版本的反应中,可能更容易获得它。
为了访问子组件中的 Props,您需要在子组件中创建一个构造函数,然后将 props 作为属性传递给 super() 函数,如下所示
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"]);
}
});
}
Run Code Online (Sandbox Code Playgroud)
完成此操作后,您可以访问整个子组件中的 props
| 归档时间: |
|
| 查看次数: |
32968 次 |
| 最近记录: |