Access this.props in responsive ComponentDidMount

I am new to react and I am stuck on a specific project. The thing is, I have api_url in this.props received from the parent component. And in this child component I want to use api_url to get some data using JSON.

In the parent component, I have:

 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"]); } }); } 

so I need the corresponding api_url in the URL section $.getJSON .

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

Another thing related to this is that I also use the $.getJSON call in the ComponentDidMount parent component.

Thanks in advance.

+14
source share
5 answers

In your class, implement the constructor:

 constructor(props){ super(props); this.state = { //states }; } componentDidMount(){ //Get this.props console.log(this.props.nameOfProp); }; 

It is probably easier to get it in this reaction version.

+6
source

To access the details in a child component, you need to create a constructor in the child component, and then pass the attribute as an attribute to the super () function as

 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"]); } }); } 

After that, you can access the details of your entire child component.

+3
source

You probably have a problem with this inside your ajax call. I assume that you need to bind this in your repositories so that the this instance in your ajax call refers to the repositories, not the ajax object.

+3
source

For those who have just stumbled upon this page, what is missing above is .bind(this) after $.getJSON . Otherwise, you will not be able to access this within $.getJSON .

 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"]); } }).bind(this); } 
0
source

You tried to add this.componentDidMount = this.componentDidMount.bind(this); to your constructor? That way you can achieve this from componentDidMount .

-2
source

Source: https://habr.com/ru/post/1012242/


All Articles