亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用條件渲染時,如何在加載頁面時渲染元素?

使用條件渲染時,如何在加載頁面時渲染元素?

千巷貓影 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 關注
  • 145 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號