Answer the question
In order to leave comments, you need to log in
Why doesn't the state of the component change?
Good day. There was such a problem. In the componentDidMount () method, I call getData (), which, in turn, accesses the server and puts the server's response into the state. But the execution of the getData method stops on the trail. code parts
this.setState({films: data}, () => {
console.log(this.state.films);
});
import React from "react";
export default class LibraryContent extends React.Component {
films = [];
constructor(props){
super(props);
this.state = {
films: []
};
this.getData = this.getData.bind(this);
}
getData(){
fetch('https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=935************d58f&language=ru')
.then(response => {
if (response.status !== 200) {
console.log('Код ошибки : ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log("Data : ");
console.log(data);
console.log("State: ");
this.setState({films: data}, () => {
console.log(this.state.films);
});
console.log("Эта строка в консоль уже не выводится");
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
};
componentDidMount(){
this.getData();
}
render() {
return (
<div>
Test
</div>
)
}
}
Answer the question
In order to leave comments, you need to log in
You are using this.setState in a function that
has its own this, not this of the LibraryContent class.
Should be replaced with an arrow function as above
This doesn't work because above this has no setState , so an error must have occurred
this.setState is not a function
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question