javascript - 使用条件渲染时,如何在加载页面时渲染元素?
问题描述
目前我的元素仅在硬重置时呈现,我认为这是因为在加载时我的状态设置为 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/>)}
解决方案
尝试这个:
componentDidMount() {
this.setState({healthData: JSON.parse(localStorage.getItem('user_data'))})
}
React 不知道状态已更新,如果您不使用setState
.
推荐阅读
- scala - 如何在scala中解析地图列表
- swift - 如何在更改嵌套数组时重新渲染?
- python - 在 Windows 上获取本地时区名称(Python 3.9 zoneinfo)
- javascript - 从两个现有数组中创建一个新数组,使用 Javascript 按 id 过滤
- node.js - 在 Nodejs/Angular 本地应用程序中使用 Oauth 的 Cors 问题
- python - 如何在 python 中使用 BeautifulSoup 抓取隐藏的表格内容?
- sql - 在 SQL Server Management Studio 中增加数据导出的 MaximumErrorCount
- spring-boot - Eureka Secured Discovery:Eureka 客户端使用端口 0 向 Eureka Server 注册
- python - 整数列用符号分隔的 Python 数据帧分析
- hive - 在 HDP 3.1 集群上执行 flink 1.10 以访问 hive 表