首页 > 解决方案 > 使用条件渲染时,如何在加载页面时渲染元素?

问题描述

目前我的元素仅在硬重置时呈现,我认为这是因为在加载时我的状态设置为 Null,IDK 如何制作它以便存储我的 div 最简单/最好的方法是什么?

 constructor(props) {
        super(props);
        this.state = {
            healthData: null
        }
    }

    componentDidMount() {
        this.state.healthData = JSON.parse(localStorage.getItem('user_data'))
    }


    render() {
        //gets users data and renders it to <p> items
        const healthData = this.state.healthData;
        console.log(healthData);
        return healthData == null ? "" : (
            <div className='main_Main'>
                <div className='meal_divs'>
                    <p className='food_heading'>Status:</p>
                    <p className='food_text'>Your age is: {this.state.healthData.age}</p>
                    <p className='food_text'>Your gender is: {healthData.gender}</p>
                    <p className='food_text'>Your goal is: {healthData.goal}</p>
                    <p className='food_text'>Your height is: {healthData.height}</p>
                    <p className='food_text'>your weight is: {healthData.weight}</p>
                </div>

请帮忙

更新:注销用户数据时登录/注销似乎是错误的,用户从本地存储中移动,然后在签名时读取,这是我的应用程序,一旦登录,您可以看到控制台日志以及我的路由器没有任何问题的事实。(忽略可怕/破碎的风格,我还没有设计它) 登录后直接页面 登录和硬重置后的页面

路由器上的条件渲染:

  {this.state.user ? (
      < Switch >
        <Route path='/setup_page' component={setup_page} exact />,
        <Route path='/settings_page' component={settings_page} exact />,
        <Route path='/' component={Main_page} />
      </Switch>
    ) : (<Login_page/>)}

标签: javascripthtmlreactjs

解决方案


尝试这个:

componentDidMount() {
  this.setState({healthData: JSON.parse(localStorage.getItem('user_data'))})
}

React 不知道状态已更新,如果您不使用setState.


推荐阅读