【问题标题】:React native fetch... Explain it like I'm 5React native fetch ......像我 5 岁一样解释它
【发布时间】:2019-05-26 14:03:56
【问题描述】:
export default class App extends Component {
  state = {
    data: []
  };

fetchData = async () => {
    const response = await fetch("https://randomuser.me/api?results=5"); // Replace this with the API call to the JSON results of what you need for your app.
    const json = await response.json(); 
    this.setState({ data: json.results }); // for the randomuser json result, the format says the data is inside results section of the json.
  }; 

所以,我在 React Native 的 App.js 文件中有这段代码。 randomuser.me 是一个只为您提供随机用户的网站。现在将其用作测试 URL。我真的不明白代码做了什么足以将它用于我项目的其他部分。我能够成功显示 5 个用户结果,但现在我想再次访问它们并遍历 state 的 data 属性。

tldr;我可以使用 data[i] 在 for 循环中访问从 fetch 中获取的数据吗?请指教。我想查看用户输入是否与存储在状态数据属性中的响应中的任何项目匹配。

【问题讨论】:

    标签: arrays json react-native iterator fetch


    【解决方案1】:

    好的,你刚刚做的就是获取。您从互联网上检索数据。 “https://randomuser.me/api?results=5”是一个 API,有很多不同的 API,每个都有自己的方式来检索数据。如果你在浏览器中输入“https://randomuser.me/api?results=5”,你会看到一个 JSON,一些 API 以 JSON 格式存储数据,另一些以数组格式存储。 在这种情况下,JSON 只有一个孩子,'results',这就是你存储“json.results”的原因。

    这是获取。你想做的只是javascript。 将 json.results 存储在变量中 然后迭代它

     var Results = json.results //store it in a variable
        for(var i = 0;i<Object.keys(Results).length;i++){ //iterate
          var CurrentUser = Results[Object.keys(Results)[i]] // i use this because some JSOn have random keys
          if(CurrentUser.gender==='male'){//if you meet a condition
          //do whatever you want
          }
    
    }
    

    如果它是一个数组,你也可以使用“.map”

    【讨论】:

    • 使用camelCase 而不是TitleCase 作为变量名,否则看起来您使用的是构造函数或类而不是对象。
    • 感谢反馈,我把变量放在了camelCase中。我把这个 for 循环放在一个处理程序中,我在主组件 App.js 的 render() 部分调用 onpress。处理程序正在被调用,但它永远不会按照 console.log 语句进入循环。当我 console.log 记录代码中结果的值时,我看到它以 Array 开头。也许它可能是一个数组?也许这是因为我用方括号将对象设置为 data[]?
    • 你是对的,在这种情况下 results 是一个对象数组。
    • 我忘记在 Object.keys() 后面加上“.length”。真的很抱歉,问题现在已经解决了。 for 循环迭代应该适用于数组和 json。
    猜你喜欢
    • 2018-12-03
    • 2014-04-10
    • 2014-02-16
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2015-04-14
    • 1970-01-01
    相关资源
    最近更新 更多