Answer the question
In order to leave comments, you need to log in
Why is this lost?
Greetings!
I'm losing this in the componentDidMount event. Broke my whole head. I thought that I understand the call context, but I don't see it. Already just copying examples from the Internet, there are working options. There is no this anyway.
Please tell me, maybe I'm just stupid?
componentDidMount = () => {
const myHeaders = new Headers({
"Content-Type": "application/json",
Accept: "application/json"
})
fetch("http://localhost:3000/bookmarks.json", {
headers: myHeaders,
})
.then(response => {
console.log(response);
return response.json();
})
.then(data => {
console.log(data);
this.setState({ data });
})
}
Answer the question
In order to leave comments, you need to log in
Here is a good answer to the question why this is lost : https://stackoverflow.com/questions/24785238/this-...
To make it work, you need to save the context in the old way:
and then refer to self when calling setState.
The working code looks like this:var self = this
componentDidMount() {
const myHeaders = new Headers({
"Content-Type": "application/json",
Accept: "application/json"
})
var self = this
fetch("https://jsonplaceholder.typicode.com/todos/1", { // ваш URL
headers: myHeaders,
}).then(response => {
return response.json();
}).then(data => {
self.setState({ data });
})
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question