for循环中的if / else语句

时间:2020-07-20 20:30:31

标签: javascript react-native redux

我有一个for循环,可从Firebase数据库收集位置。根据这些数据,我还可以计算出用户手机与其自身位置之间的距离。

如果找不到userData,我的应用程序现在会中断,因此我想为用户位置不存在创建故障保护。但是我不能使它工作...如果没有触发if AND else语句的console.log条目。我也没有看到“此功能是否在外部工作”注释。对我来说太晚了,所以也许我错过了明显的东西?

for (const key in resData) {
    const reduxUserLocation = getState().locationActions.userLocation

    if (reduxUserLocation === null) {
    const calculateDistance = getDistance(
        { latitude: resData[key].location[0].lat, longitude: resData[key].location[0].lng },
        { latitude: reduxUserLocation.lat, longitude: reduxUserLocation.lng }
    )
    console.log('distance?' , calculateDistance)

    loadLocations.push(
        new ReportedLocations(
            key,
            resData[key].ownerId,
            resData[key].location,
            resData[key].description,
            resData[key].streetname,
            resData[key].placename,
            resData[key].date,
            calculateDistance
        )
    );
        }
        else {
            console.log("user location isn't found")
            const calculateDistance = 0

            loadLocations.push(
                new ReportedLocations(
                    key,
                    resData[key].ownerId,
                    resData[key].location,
                    resData[key].description,
                    resData[key].streetname,
                    resData[key].placename,
                    resData[key].date,
                    calculateDistance
                )
            );        
        }
        console.log('Does this work outside the if/else statement?')
}

2 个答案:

答案 0 :(得分:1)

如果不查看用于Firestore查询的代码,则很难调试。如果我不得不猜测,我会考虑使用对documentation中所示的SDK的调用来检查是否有空文档/查询。我根据您的代码在文档中自定义了示例代码。

这是读取单个文档的一些代码。

let resData;
const doc = await cityRef.get();
if (!doc.exists) {
  console.log('No such document!');
  resData = null
} else {
  resData = doc.data();
}

和收藏

let resDataArr = []
const snapshot = await citiesRef.where('capital', '==', true).get();
if (snapshot.empty) {
  console.log('No matching documents.');
  resDataArr = [null]
} else {
  snapshot.forEach(doc=> resDataArr.push(doc.data()) );
}

如果您使用的是库,则可能会更改。我没有测试此代码,因此可能会出现一两个语法错误。

答案 1 :(得分:1)

因此,看来您正在尝试从reduxUserLocation检索为空值的经度/纬度值

if (reduxUserLocation === null) {
    const calculateDistance = getDistance(
        { latitude: resData[key].location[0].lat, longitude: resData[key].location[0].lng },
        { latitude: reduxUserLocation.lat, longitude: reduxUserLocation.lng } // THIS LINE
    )

显然这是不可能的,并且会引发错误。因此,您在其下方看不到任何日志行。

此外,我相信您的if陈述有误。似乎您想尽可能地计算距离,否则应该为0。if语句则相反。

除此之外,使用for-in循环时还有一个陷阱。最好总是检查hasOwnProperty

如果您只想考虑附加到对象本身的属性,而不是对象的原型,请使用getOwnPropertyNames()或执行hasOwnProperty()检查(也可以使用propertyIsEnumerable())。另外,如果您知道不会受到任何外部代码的干扰,则可以使用check方法扩展内置原型。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

在这里,我认为应该是正确的代码

for (const key in resData) {
  // Check if key is a property, if not, skip this iteration
  if (!resData.hasOwnProperty(key)) {
    continue;
  }

  const reduxUserLocation = getState().locationActions.userLocation;

  let calculateDistance = 0; // Set default distances to 0

  // If location is present, use that to calculate the distance and overwrite the variable above
  if (reduxUserLocation){
    calculateDistance = getDistance(
      {latitude: resData[key].location[0].lat, longitude: resData[key].location[0].lng},
      {latitude: reduxUserLocation.lat, longitude: reduxUserLocation.lng}
    );
  }
 
  // Moved push to array after the if-statement -> DRY (Don't Repeat Yourself)
  loadLocations.push(
    new ReportedLocations(
      key,
      resData[key].ownerId,
      resData[key].location,
      resData[key].description,
      resData[key].streetname,
      resData[key].placename,
      resData[key].date,
      calculateDistance
    )
  );
}