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

目前我的元素仅在硬重置时呈现,我认为这是因为加载时我的状态设置为 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>

请帮忙



千巷猫影
浏览 103回答 3
3回答

摇曳的蔷薇

尝试这个:componentDidMount() {&nbsp; this.setState({healthData: JSON.parse(localStorage.getItem('user_data'))})}React 不知道状态已更新,如果您不使用setState.

慕桂英546537

有一些事情可能会导致问题。您没有setState()在您的componentDidMount()componentDidMount() {&nbsp; &nbsp; this.setState({&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; healthData: JSON.parse(localStorage.getItem('user_data'))&nbsp; &nbsp; });}您可以从使用您的语法healthData && <div />中受益render()render() {&nbsp; &nbsp; //gets users data and renders it to <p> items&nbsp; &nbsp; const healthData = this.state.healthData;&nbsp; &nbsp; return healthData && <div className='main_Main'>...</div>;}

慕码人2483693

您直接改变 componentDidMount 方法中的状态。这不是反应的目的。相反,您使用 setState 方法设置状态,并且组件将重新渲染。&nbsp;componentDidMount() {&nbsp; &nbsp; this.setstate({healthData : JSON.parse(localStorage.getItem('user_data'))})}在渲染方法中,您可以使用对象解构来保存状态健康数据,如下所示,并在条件渲染中编辑以下代码,如下所示 -const { healthData } = this.state;return(&nbsp; <div className='main_Main'>&nbsp; &nbsp; &nbsp; &nbsp;<div className='meal_divs'>&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; healthData === null ? "" :&nbsp;&nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p className='food_heading'>Status:</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p className='food_text'>Your age is: {healthData.age}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p className='food_text'>Your gender is: {healthData.gender}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p className='food_text'>Your goal is: {healthData.goal}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p className='food_text'>Your height is: {healthData.height}</p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p className='food_text'>your weight is: {healthData.weight}</p>&nbsp; &nbsp; &nbsp; &nbsp;)&nbsp; &nbsp; }&nbsp;</div>&nbsp;</div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5