json 我应该如何在我的组件中引用来自我的API的数据?

yrwegjxp  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(77)

App.js

import { Text, View, Button, FlatList } from 'react-native';
import { useEffect, useState } from 'react';
import * as React from 'react';

const API = 'https://randomuser.me/api/users/';

const User = (props) => (
  <View>
    <Text>Name: {props.fname} {props.lname}</Text>
    <Text>Country: {props.country}</Text>
  </View>
);
const renderUser = ({item}) => <User fname={item.results[0].name.first} lname={item.results[0].name.last} country={item.results[0].location.country}/>;

export default function App() {
  const [users, setUsers] = useState({});

  useEffect(() => {
  fetch(API)
  .then((response) => response.json())
  .then((json) => {setUsers(json);});}, []);

  return (
    <View>
      <Text>{}</Text>

      <Button title="add a user" onPress={() => {
        fetch(API)
        .then((response) => response.json())
        .then((json) => {setUsers(json);}), []}}
      />

      <FlatList data={users} renderItem={renderUser}/>

    </View>
  );
}

当我创建一个用户时,我应该如何引用json中的名字和姓氏以及国家?在网上看过之后,我认为这个(item.results [0]. name.first)是我应该引用它的方式,但它仍然不起作用。我做错了什么

nsc4cvqm

nsc4cvqm1#

您似乎设置了错误的API。我只是测试:
https://randomuser.me/api/返回正确的结果。
https://randomuser.me/api/users/返回404 not found

更新:

API的响应是:

{
  "results": [
    {
      "gender": "male",
      "name": {
        "title": "Mr",
        "first": "Harley",
        "last": "Green"
      },
      "location": {
        "street": {
          "number": 5662,
          "name": "Hoon Hay Road"
        },
      }
    }
  ]
}

所以你需要编辑你的代码:

...
const renderUser = ({ item }) => {
  return (
    <>
      <User
        fname={item.name.first}
        lname={item.name.last}
        country={item.location.country}
      />
    </>
  );
};

export default function App() {
   return (
    <>
      <View>
        <Button
          title="add a user"
          onPress={() => {
            fetch(API)
              .then((response) => response.json())
              .then((json) => {
                setUsers(json);
              }),
              [];
          }}
        />

      
        <FlatList data={users.results} renderItem={renderUser} />
      </View>
    </>
  );
}

相关问题