首页 > 解决方案 > 如何在本机反应中从假服务器获取数据?

问题描述

我在笔记本电脑中制作了一个假服务器来获取数据。这是其中的数据:

[
  {
    "id": 1,
    "firstName": "Bill",
    "lastName": "Gates",
    "email": "bill@microsoft.com",
    "phone": "1234567898",
    "role": "Accountant",
    "org": "Organization 1"
  },
 {
    "id": 2,
   "firstName": "Mark",
   "lastName": "Zuckerberg",
   "email": "mark@facebook.com",
   "phone": "9876543212",
   "role": "Admin",
   "org": "Organization 1"
  }
]

我使用 npm run mock:api 运行服务器

我想从中获取数据并显示在我的物理 android 设备(手机)中。这是我尝试过的代码:

constructor(props) {
    super(props);

    this.state = {
        users_fake: []
    }
}

componentDidMount() {

    fetch("https://192.168.43.164:4000/users")
    .then(response => response.json())
    .then((responseJson)=> {
        console.log('Response = ' + responseJson);
        this.setState({
            loading: false,
            users_fake: responseJson
        })
    })
    .catch(error=>console.log(error))

和这个:

  fetch("http://localhost:4000/users")
        .then(response => response.json())
        .then((responseJson)=> {
        this.setState({
        loading: false,
        users_fake: responseJson
        })
        })
        .catch(error=>console.log(error))

和这个:

 fetch('http://localhost:4000/users', {
            method: 'GET'
         })
         .then((response) => response.json())
         .then((responseJson) => {
            console.log(responseJson);
            this.setState({
               users_fake: responseJson
            })
         })
         .catch((error) => {
            console.error(error);
         });

}

我显示这样的数据:

 { this.state.users_fake.map((user, index) => { 
     return (
         <Text>{user.firstName} {user.lastName}</Text>
     )
 })}

但我在控制台中收到错误:

WARN  Possible Unhandled Promise Rejection (id: 16):
TypeError: Network request failed

我应该怎么做才能获取数据并显示它?

标签: typescriptreact-nativefetch

解决方案


在 catch 函数中添加抛出错误

fetch("https://192.168.43.164:4000/users")
    .then(response => response.json())
    .then((responseJson)=> {
        console.log('Response = ' + responseJson);
        this.setState({
            loading: false,
            users_fake: responseJson
        })
    })
    .catch(error=>{console.log(error);
throw error;})

希望这可以帮助!


推荐阅读