为了账号安全,请及时绑定邮箱和手机立即绑定

使用条件渲染时,如何在加载页面时渲染元素?

使用条件渲染时,如何在加载页面时渲染元素?

千巷猫影 2023-10-10 09:32:58
目前我的元素仅在硬重置时呈现,我认为这是因为加载时我的状态设置为 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>请帮忙
查看完整描述

3 回答

?
摇曳的蔷薇

TA贡献1793条经验 获得超6个赞

尝试这个:


componentDidMount() {

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

}

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


查看完整回答
反对 回复 2023-10-10
?
慕桂英546537

TA贡献1848条经验 获得超10个赞

有一些事情可能会导致问题。


您没有setState()在您的componentDidMount()

componentDidMount() {

    this.setState({ 

        healthData: JSON.parse(localStorage.getItem('user_data'))

    });

}

您可以从使用您的语法healthData && <div />中受益render()

render() {

    //gets users data and renders it to <p> items

    const healthData = this.state.healthData;

    return healthData && <div className='main_Main'>...</div>;

}


查看完整回答
反对 回复 2023-10-10
?
慕码人2483693

TA贡献1860条经验 获得超9个赞

您直接改变 componentDidMount 方法中的状态。这不是反应的目的。相反,您使用 setState 方法设置状态,并且组件将重新渲染。


 componentDidMount() {

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

}

在渲染方法中,您可以使用对象解构来保存状态健康数据,如下所示,并在条件渲染中编辑以下代码,如下所示 -


const { healthData } = this.state;

return(

  <div className='main_Main'>

       <div className='meal_divs'>

   {

      healthData === null ? "" : 

      (

          <p className='food_heading'>Status:</p>

          <p className='food_text'>Your age is: {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>

 </div>


查看完整回答
反对 回复 2023-10-10
  • 3 回答
  • 0 关注
  • 70 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信