Reactjs Storing State In Constructor Vs Property
I have a very simple react component that needs to connect to an API and retrieve some JSON data, which will then be used for displaying some information. In the following class/co
Solution 1:
Initializing state in the constructor like your second example is perfectly valid, but your two examples are not the same. You are setting isLoading
to true
in the class property version, but isLoading
to false
in the constructor.
If error
in null
and isLoading
is false
you will hit the last part of your render method. Since projectInfo
is null
before your request is complete, you will try to access name
on null
and get your error.
Set isLoading
to true
and it should work as expected, or even projectInfo
to an empty object {}
, but then you will not get the loading indicator.
classMyReportSummaryextendsComponent{
constructor(props) {
super(props);
this.mounted = true;
this.state = {
projectInfo: {},
isLoading: true,
error: null
};
}
// ...
}
Post a Comment for "Reactjs Storing State In Constructor Vs Property"