pouchdb / react,如果数据库中没有结果,则将状态值设置为零

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

我有一段代码块,只要数据库中有东西,它们就可以正常工作,但这会导致应用程序在首次加载时崩溃,因为新部署的数据库中没有结果集。现在,如果我设置数据并加载此屏幕,它将从pouchdb获取结果集并获取doc,然后根据文档索引设置状态值。

当前在新负载下,我收到一个错误,即它无法读取newBaselineDocs[0]的undefined属性>

我需要更改它,以便如果数据库没有结果,那么我将这些值的状态全部设置为零。

例如,如果没有结果,那么我会使用ldl: newBaselineDocs[0].ldl代替ldl: 0。我知道那将是一个if / else的东西,但是我不知道;我真的不知道如何使用pouchdb结果逻辑来实现它。

setBaselineMax = () => {
    this.state.baselineDB.db.find({
      selector: {
        $and: [
          {_id: {"$gte": null}},
          {ldl: {$exists:true}},
          {hdl: {$exists:true}},
          {totalChol: {$exists:true}},
          {weight: {$exists:true}},
          {water: {$exists:true}},
          {sleep: {$exists:true}},
          {activity: {$exists:true}},
          {heartRate: {$exists:true}},
          {netCalories: {$exists:true}},
          {bloodPresure: {$exists:true}},
          {whiteCount: {$exists:true}},
          {redCount: {$exists:true}},
          {trig: {$exists:true}},
          {glucose: {$exists:true}},
          {oxygen: {$exists:true}},
          {psa: {$exists:true}},
          {alcohol: {$exists:true}},
          {createdAt: {$exists: true}}

        ]
      },
      fields: ['_id','ldl','hdl','totalChol','weight','water','sleep','activity','heartRate','netCalories','bloodPresure','whiteCount','redCount','trig','glucose','oxygen','psa', 'alcohol'],
      sort: [{'_id':'asc'}],
      limit: 1
    }).then(result => {
      console.log('baseline result');
      console.log(result);

      const newBaselineDocs = result.docs;

      console.log('this is basline data from app');
      console.log(newBaselineDocs);

      this.setState(prevState => ({
        baselineRecord: {                   // object that we want to update
            ...prevState.baselineRecord,    // keep all other key-value pairs
            ldl: newBaselineDocs[0].ldl,
            hdl: newBaselineDocs[0].hdl,
            totalChol: newBaselineDocs[0].totalChol,
            weight: newBaselineDocs[0].weight,
            water: newBaselineDocs[0].water,
            sleep: newBaselineDocs[0].sleep,
            activity: newBaselineDocs[0].activity,
            heartRate: newBaselineDocs[0].heartRate,
            netCalories: newBaselineDocs[0].netCalories,
            bloodPresure: newBaselineDocs[0].bloodPresure,
            whiteCount: newBaselineDocs[0].whiteCount,
            redCount: newBaselineDocs[0].redCount,
            trig: newBaselineDocs[0].trig,
            glucose: newBaselineDocs[0].glucose,
            oxygen: newBaselineDocs[0].oxygen,
            psa: newBaselineDocs[0].psa,
            alcohol: newBaselineDocs[0].alcohol     // update the value of specific key
        }
      }))

我有一段代码块,只要数据库中有东西,它就可以正常工作,但这会导致应用程序在第一次加载时崩溃,因为新数据库中没有结果集...

reactjs pouchdb
1个回答
0
投票

这确实应该在评论中,但是那样会很丑陋。因为result.docs为空,而您的代码假定它永远都不为空,所以会出现此错误。

由于newBaselineDocs为空,因为result.docs为空,所以newBaselineDocs[0][someProperty]未定义。

© www.soinside.com 2019 - 2024. All rights reserved.