反应本机获取...像我5岁一样解释


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.
  }; 

所以,我在我的 App.js 文件中有这段代码,用于 React Native。randomuser.me 是一个只给你随机用户的网站。立即将其用作测试 URL。我真的不明白代码做了什么,以至于能够将其用于项目的其他部分。我能够成功显示 5 个用户结果,但现在我想再次访问它们并循环访问状态的数据属性。

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

好的,你刚刚做的,那就是获取。您从互联网检索数据。"https://randomuser.me/api?results=5"是一个API,有很多不同的API,每个API都有自己的方式来检索数据。如果你在浏览器中输入"https://randomuser.me/api?results=5",你会看到一个JSON,一些API以JSON形式存储数据,其他API以数组格式存储数据。在这种情况下,JSON只有一个子项,"结果",这就是存储"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"

最新更新