【问题标题】:react native : there is way to message to the screen if axios id fail?反应原生:如果 axios id 失败,有办法向屏幕发送消息吗?
【发布时间】:2020-03-05 12:50:22
【问题描述】:

当 get axios 失败时,有办法在屏幕上显示消息。 怎么办?

这是我的示例代码:

getData = () => {
    this.setState({ isLoading: true, data: [] });
    var userPrincipalName = this.state.userPrincipalName;
    ///for debbugin only--NEED TO CHANGE "THE_NAME_USER" TO "userPrincipalName" IN THE AXIOS
    THE_NAME_USER = "apaz";
    axios
      .get(
        "https://harigotphat1.mekorot.co.il/ConfirmPackaotWS/OrderApprove/OrderApp_Get_Orders_To_Approve/" +
          THE_NAME_USER
      )
      .then(res => {
        this.setState({
          isLoading: false,
          data: res.data
        });
        InfoStore.setList(res.data);
      });
  };

【问题讨论】:

    标签: javascript reactjs react-native axios expo


    【解决方案1】:

    当 API 发生故障时,有多种方法可以显示错误消息。

    检查以下示例并根据您的要求进行更改。

    import React from "react";
    import { FlatList, ActivityIndicator, Text, View } from "react-native";
    import axios from "axios";
    
    export default class Example extends React.Component {
        state = {
            isLoading: true,
            isError: false
        };
    
        componentDidMount() {
            return axios
                .get("https://reactnative.dev/movies.json")
                .then(response => {
                    this.setState({
                        isLoading: false,
                        data: response.data.movies
                    });
                })
                .catch(error => {
                    this.setState({
                        isLoading: false,
                        isError: true
                    });
                });
        }
    
        render() {
            return (
                <View style={{ flex: 1, paddingTop: 20 }}>
                    {
                        // Shows loding indicator until data loads
                        this.state.isLoading ?
                            <View style={{ flex: 1, padding: 20 }}>
                                <ActivityIndicator />
                            </View>
                            :
                            // Shows an error if an error occured
                            this.state.isError ?
                                <View style={{ flex: 1, padding: 20, alignItems: 'center' }}>
                                    <Text>Oops ? error while loading</Text>
                                </View>
                                :
                                // Display data after successful fetch 
                                <FlatList
                                    data={this.state.data}
                                    renderItem={({ item }) => (
                                        <Text>
                                            {item.title}, {item.releaseYear}
                                        </Text>
                                    )}
                                    keyExtractor={({ id }, index) => id}
                                />
                    }
                </View>
            );
        }
    }
    

    希望这对您有所帮助。如有疑问,请随意。

    【讨论】:

      【解决方案2】:

      是的,有可能,像这样使用两个“.then”语句

      axios.get("https://harigotphat1.mekorot.co.il/ConfirmPackaotWS/OrderApprove/OrderApp_Get_Orders_To_Approve/" +
                THE_NAME_USER
            ).then(response =>
        {
          const statusCode = response.status;
          const data = response.json();
          return Promise.all([statusCode, data]);
        }).then(res => {
                      this.setState({
                          isLoading: false,
                          data: res.data
                      });
                      InfoStore.setList(res.data);
                      // console.log("InfoStore get;List", InfoStore.getList.slice());
                  }).catch(error => {
                      console.log(error);
                      alert(“your error is here”)
              });
      

      首先“.then”实际处理您的 API 调用的 HTTP 响应,如果它不工作或发生错误,那么它会给出相应的错误代码(例如,在成功的情况下它使“200 OK”和错误情况下返回 500 或其他错误代码)。您可以轻松地在这些状态代码上显示警报并相应地检查您的 api 调用数据。此链接上提供了错误代码说明 https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

      【讨论】:

      • 你能解释更多吗,实际上你需要什么?
      • 我需要写信来屏蔽这条消息:“嗨,这是错误”
      • 我编辑了我的代码,你能在我的新更改中告诉我如何将消息“嗨,这是错误”发送到屏幕吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多