在React中不断得到未定义的错误并放大

问题描述 投票:0回答:1

我正在尝试在我的反应项目中对发电机数据库执行列表查询,但我不断收到以下错误

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>

如果您需要查看更多代码,我会将其添加进去。我无法弄清楚如何解决这个问题。任何帮助解决这个问题将非常感激。谢谢!

reactjs aws-appsync aws-amplify
1个回答
1
投票

this.state.patients是异步填充的,这意味着你必须确保它的默认值是空数组,这样,即使你尝试使用patients.map,render()也不会得到运行时错误。把它想象为[].map有效,但undefined.map没有。试试这个:

更换

const { patients } = this.state;

const { patients = [] } = this.state;
© www.soinside.com 2019 - 2024. All rights reserved.