Answer the question
In order to leave comments, you need to log in
Why is state not read in react?
I don’t understand why the state is not read
When I output to the console when the state is Initialized, everything is fine and everything is displayed
, but in the render the console does not see anything further than "form"
import React, { Component, Fragment } from "react";
import Form from "./components/Form.js";
class App extends Component {
constructor() {
super();
this.state = {
components: {},
form: {},
data: {}
};
}
async componentDidMount() {
let response = await fetch(
"https://gist.githubusercontent.com/alexandrov-va/7f353ca822d074d7ce22d3af3d13696f/raw/0907091de6fedf6153cdb718f32a4215dc2c53cf/page.json"
);
let data = await response.json();
this.setState({
components: data.components,
form: data.form,
data
});
console.log(data.form.submit_button.text);
}
render() {
console.log(this.state.data.form.submit_button.text)
return (
<Fragment>
<Form />
</Fragment>
);
}
}
export default App;
Answer the question
In order to leave comments, you need to log in
Because the data comes in asynchronously and on the first render, the state is literally like this:
this.state = {
components: {},
form: {},
data: {}
};
Because fetch is an asynchronous function.
In the componentDidMount function, the this.setState function will be called only when the response from the request https://gist.githubusercontent ..... first, render will be called and this.state.form will show an empty object in the console, and later, after the request is executed, this.state.form will already take on a new value.
it's just that if I'm rendering in view of the console.log(this.state.data) in the console, then it will calmly give the object in the console and without any errors, but if I enter console.log(this.state.data.form.submit_button.text) then the error TypeError: Cannot read property 'submit_button' of undefined is displayed
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question