【问题标题】:How to check if a JSON object is present in a file in JavaScript如何检查 JSON 对象是否存在于 JavaScript 中的文件中
【发布时间】:2019-08-07 20:19:19
【问题描述】:

我正在用 react-native 构建一个应用程序,并且在进行错误检查时遇到了一些麻烦。我正在使用reduxthunk 从我正在搜索的API 中存储一个JSON 文件。有时,搜索会返回一个包含错误消息的 JSON 文件(很可能是由于拼写错误或不确定我正在搜索的内容)。我正在尝试在我的应用程序中构建一个函数,该函数将在 componentWillMount 函数中运行,该函数首先检查文件是否有错误消息,如果有,则将其发送回主屏幕以重做搜索。我遇到的问题是我不知道要编写什么代码才能查看错误是什么,或者即使有错误开始。

这是错误对象在 JSON 文件中的样子,而这个

"error": {
    "type": "NameResolutionException",
    "message": "Name resolution error: Taxon 'Mallard' or 'Bat' resolve to multiple nodes"
  },

这是我构建的函数

componentDidMount = () => {
    console.log("STATE", this.state);
    if(this.props.response.articles.error == undefined){
      if(this.props.response.articles.error.type === "NameResolutionException"){
        Alert.alert("Please Refine Search or Specify Taxon.")
          .then(()=>this.props.navigation.navigate("Home"));
      }
    }
 };

尽管 json 文件将包含错误对象,但 if 语句永远不会命中。

预期的输出是错误将被捕获,然后应用程序将返回其主屏幕,但应用程序将失败,因为某些组件将丢失。

【问题讨论】:

  • 我敢打赌 articles 是一个数组,而不是一个对象,所以你需要索引它。
  • 希望!= undefined在第一个if

标签: javascript json react-native


【解决方案1】:

您的代码似乎不正确,您是说如果错误未定义,则比较字符串值。这是矛盾的。

应该是这样的,考虑到错误是一个对象而不是一个数组

componentDidMount = () => {
console.log("STATE", this.state);
if(this.props.response.articles.error && this.props.response.articles.error.type){ // considering error object may or may not be present
  if(this.props.response.articles.error.type === "NameResolutionException"){
    Alert.alert("Please Refine Search or Specify Taxon.")
      .then(()=>this.props.navigation.navigate("Home"));
  }
  else if (this.props.response.articles.error.type === "OtherPossibleStringException"){
  }
  else {
      //Any unhandled error case
  }
 }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多