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)是我应该引用它的方式,但它仍然不起作用.我做错了什么?

推荐答案

看起来您设置了错误的接口.我只是测试一下:

https://randomuser.me/api/将返回正确的结果.

https://randomuser.me/api/users/返回404 not found.

UPDATE:

接口的响应为:

{
  "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>
    </>
  );
}

Javascript相关问答推荐

Codemirsor 6语言包的使用部分是什么?

在JavaScript中使用setProperty方法试图修改css元素值时,我遇到错误

在JS中转换mysql UTC时间字段?

为什么这个自定义组件会被放置在TR之外?

基于每个索引迭代嵌套对象

React存档iframe点击行为

单击更新页面的按钮后,页面刷新;测试/断言超时,有两个标题,但没有一个标题

使用下表中所示的值初始化一个二维数组

如何在JavaScript文件中使用Json文件

Javascript json定制

如何发送从REST Api收到的PNG数据响应

OpenAI转录API错误请求

MarkLogic-earch.suggest不返回任何值

try 使用PM2在AWS ubuntu服务器上运行 node 进程时出错

按下单键和多值

Reaction-SWR-无更新组件

警告框不显示包含HTML输入字段的总和

在Odoo中如何以编程方式在POS中添加产品

使用Reaction窗体挂钩注册日历组件

更改agGRID/Reaction中的单元格格式