javascript - 当我输入我的 react js 组件时它运行良好但是当我重新加载浏览器时它给我错误无法读取未定义的属性“值”
问题描述
这是 App js 从“react”导入 React
import React from "react"
import {Cards , Chart , CountryPicker} from "./Components"
import styles from "./App.module.css"
import {fetchData} from "./api"
class App extends React.Component{
state = {
data : {},
}
async componentDidMount() {
const fetchedData = await fetchData()
this.setState({data : fetchedData})
}
render() {
return (
<div className={styles.container}>
<Cards data={this.state.data}/>
<CountryPicker />
<Chart />
</div>
)
}
}
export default App
import React from "react"
import {Card, CardContent, Typography, Grid} from '@material-ui/core'
import styles from "./Cards.module.css"
import CountUp from "react-countup"
const Cards = (props) => {
console.log(props)
return (
<div className={styles.container}>
<Grid container spacing={3} justify="center">
<Grid item component={Card}>
<CardContent>
<Typography color="textSecondary" gutterBottom>Infected</Typography>
<Typography variant="h5"><CountUp start={0} end={props.data.confirmed.value} separator="," duration={2} /></Typography>
<Typography color="textSecondary">{new Date(props.data.lastUpdate).toDateString()}</Typography>
<Typography variant="body2">Number of Active cases of Covid-19</Typography>
</CardContent>
</Grid>
<Grid item component={Card}>
<CardContent>
<Typography color="textSecondary" gutterBottom>Recovered</Typography>
<Typography variant="h5"><CountUp start={0} end={props.data.recovered.value} separator="," duration={2} /></Typography>
<Typography color="textSecondary">{new Date(props.data.lastUpdate).toDateString()}</Typography>
<Typography variant="body2">Number of Recoveries from Covid-19</Typography>
</CardContent>
</Grid>
<Grid item component={Card}>
<CardContent>
<Typography color="textSecondary" gutterBottom>Deaths</Typography>
<Typography variant="h5"><CountUp start={0} end={props.data.deaths.value} separator="," duration={2} /></Typography>
<Typography color="textSecondary">{new Date(props.data.lastUpdate).toDateString()}</Typography>
<Typography variant="body2">Number of Deaths caused by Covid-19</Typography>
</CardContent>
</Grid>
</Grid>
</div>
)
}
export default Cards
'''
解决方案
因为初始状态是未定义的。将您的代码放在 if 语句中,这样它就不会出错。
<div className={styles.container}>
if(this.state) {
<Cards data={this.state.data}/>
} else {
<p>Loading data...</p>
}
<CountryPicker />
<Chart />
</div>
推荐阅读
- c# - 在客户端标头 C# 中设置基本身份验证
- java - 如何在一定时间后结束 do while 循环?
- ruby-on-rails - 载波如何更改文件名?
- python - 如何从数据框中删除不在python列表中的单词
- laravel - Laravel 6 的登录表单
- java - Java,如何在泛型中进行比较
- bash - 如何从字符串中提取数字但保留小数?
- python-3.x - Python从json聚合数据
- javascript - TypeError:按下任何键时无法读取null的属性“名称”反应reactjs javascript redux
- compilation - 当我们有反编译器时,为什么我们需要检测二进制文件?