如何在reactjs和awsamplify中执行多个查询

时间:2019-03-15 12:01:54

标签: javascript reactjs amazon-dynamodb aws-appsync aws-amplify

我正在尝试在React.js中查询多个1个Dynamo数据库。我尝试在不同的类中定义这两个组件,然后将其导入,这是行不通的,然后尝试在同一类中定义这两个组件,这给了我错误

TypeError: this.state.patients2 is undefined

这是我的组成部分

 state = { patients2: [] }


 async componentDidMount() {
    try {
      const apiData = await API.graphql(graphqlOperation(listPatients2))
      const patients2 = apiData.data.listPatients2.items
      this.setState({ patients2 })
    } catch (err) {
      console.log('qqqqqqqqqqqqqqqqqq ', err)
    } 
  } 

 state = { beraters: [] }
  async componentWillMount2() {
    try {
      const apiData = await API.graphql(graphqlOperation(listBeraters))
      const beraters = apiData.data.listBeraters.items
      this.setState({ beraters })
      console.log(beraters)
    } catch (err) {
      console.log('qqqqqqqqqqqqqqqqq ', err

)
    }
  } 

在这里我映射结果

<h1>Meine Daten</h1>


    {
          this.state.beraters.map((rest, i) => (
            <div style={styles.item}>
              <p style={styles.Vorname}>{rest.Vorname}</p>
              <p style={styles.Nachname}>{rest.Nachname}</p>
              <p style={styles.Strasse}>{rest.Strasse}</p>
              <p style={styles.Hausnr}>{rest.Hausnr}</p>
              <p style={styles.Ort}>{rest.Ort}</p>
              <p style={styles.Postleitzahl}>{rest.Postleitzahl}</p>
              <p style={styles.Telefonnummer}>{rest.Telefonnummer}</p>
            </div>
          ))
         }
      </div>

<div >
    {
          this.state.patients2.map((rest, i) => (
            <div style={styles.item}>
              <l style={styles.Vorname}>{rest.Vorname}</l>
              <l>  </l>
              <l style={styles.Nachname}>{rest.Nachname}</l>
            </div>
          ))


        }
      </div>

非常感谢您的帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

您的患者2是未定义的,因为您正在覆盖状态值。只需一起定义状态中的数组,并同时调用查询即可。像这样:

state = {
  beraters: [],
  patients2: []
}
async componentDidMount() {
    try {
      const apiDataPatients = await API.graphql(graphqlOperation(listPatients2))
      const apiDataBeraters = await API.graphql(graphqlOperation(listBeraters))
      const patients2 = apiDataPatients.data.listPatients2.items
      const beraters = apiDataBeraters.data.listBeraters.items
      this.setState({ beraters, patients2 })
    } catch (err) {
      console.log('Error:', err)
    } 
}