React Typescript:重新加载页面后获取sessionStorage

React Typescript: get sessionStorage after reload of page

用户登录后,身份验证令牌会保存在 sessionStorage 中,页面会重新加载。现在重新加载后,我想读取该数据并将其存储在 state 中,但渲染不会从 <Login /> 更改为 <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 });
   }

Do not call setState() in constructor(). Instead, if a component needs to use a local state, assign the initial state to this.state directly in the constructor.

componentDidMount() invokes immediately after a component mounts. You can call setState() immediately in componentDidMount() and triggers an extra rendering, but this happens before the browser updates the screen, calling render() twice.

read more here

您可以 return 来自 _auth 方法的 sessionStorage 的值并使用该值在构造函数中创建状态,或者您可以简单地调用 this._auth 在 componentDidMount() 里面仍然可以,但主要用于异步计算、副作用等