Reactjs 在反应和放大过程中不断出现未定义的错误
我试图在我的react项目中对dynamo数据库执行列表查询,但我一直遇到以下错误Reactjs 在反应和放大过程中不断出现未定义的错误,reactjs,aws-appsync,aws-amplify,Reactjs,Aws Appsync,Aws Amplify,我试图在我的react项目中对dynamo数据库执行列表查询,但我一直遇到以下错误 TypeError: patients is undefined render C:/Health Project/nutzer-system/src/PatientComponents/listPatients.js:62 59 | console.log(patients) 60 | return ( 61 | <div className={classes.root}> &
TypeError: patients is undefined
render
C:/Health Project/nutzer-system/src/PatientComponents/listPatients.js:62
59 | console.log(patients)
60 | return (
61 | <div className={classes.root}>
> 62 | <Grid container className={classes.root} spacing={16}>
| ^ 63 | {patients.map( patient => (
64 | <Grid key={patient.id} patient>
65 | <Card className={classes.card}>
下面是我的代码的更多部分
state = {
patients: []
}
componentDidMount = () => {
this.getPatients()
}
getPatients = () => {
API.graphql(graphqlOperation(queries.listPatients))
.then(data => this.setState({patients: data.data.listPatients.patients}))
};
render(){
const { classes } = this.props;
const { patients } = this.state;
console.log(patients)
return (
<div className={classes.root}>
<Grid container className={classes.root} spacing={16}>
{patients.map( patient => (
<Grid key={patient.id} patient>
<Card className={classes.card}>
<CardContent>
<Typography className={classes.title} color="textSecondary" gutterBottom>
{patient.Vorname}
</Typography>
<Typography component="p">
{patient.Nachname}
</Typography>
<Typography component="p">
{patient.Strasse}
</Typography>
如果你需要看到更多的代码,只需说,我会添加它。我想不出怎么解决这个问题。如果您能帮助解决此问题,我们将不胜感激。谢谢 this.state.patients是异步填充的,这意味着您必须确保它的默认值为空数组,这样,即使尝试使用patients.map,渲染也不会得到运行时错误。可以将其视为[]。map可以工作,但undefined.map不能。试试这个: 替换
const { patients } = this.state;
与
你确定data.data.listPatients.patients不是未定义的吗?是的,非常确定它不是console.logpatients返回的是什么?它返回数据库中各种元素的数组我看不出问题所在。你能提供更多的代码吗?他的默认状态是一个空数组啊,我不好,我没注意。所以,是的,我们需要知道console.logpatients显示了什么。我认为这是正确的,它将处理患者在getPatients中更新为未定义的情况。它将覆盖初始空数组状态
const { patients = [] } = this.state;