After the User Sign In, a authentication token is saved in the sessionStorage and the Page gets Reloaded. Now after the reload I want to read that data and store it in a state but the render dont change from <Login /> to <Layout>...
export default class Home extends React.Component<any, State> {
constructor(props: any) {
super(props);
this.state = {
auth: true,
}
this._auth();
}
public render() {
return (
<>
{this.state.auth ?
<Login /> :
<Layout>
...
</Layout>
</>
)
};
private _auth(): void {
if (sessionStorage.getItem("accessGranted") !== "")
this.setState({ auth: true });
else
this.setState({ auth: false });
}
CodePudding user response:
Do not call
setState()inconstructor(). Instead, if a component needs to use a local state, assign the initial state tothis.statedirectly in the constructor.
componentDidMount()invokes immediately after a component mounts. You can callsetState()immediately incomponentDidMount()and triggers an extra rendering, but this happens before the browser updates the screen, callingrender()twice.
Either you can return the value of your sessionStorage from _auth method and use that value to create the state inside the constructor, OR you can simply call this._auth inside componentDidMount() which is still okay but mainly used for async computations, side effects etc.
