在与axios的反应中添加全局微调器

问题描述 投票:2回答:2

我正在使用react native和axios来调用HTTP请求。我显示微调框的操作是在调用HTTP请求之前将在我的组件状态下的Loading设置为true,在获取数据或发生错误后将其设置为false。然后我有一个微调器组件,并根据isLoading值显示它。是否有可能不需要我所有组件中的上述功能的全局微调器?我认为axios中的拦截器可以帮助解决此问题吗?

react-native spinner loading react-navigation interceptor
2个回答
1
投票

有一些可用的软件包,但我建议您以自己的方式进行设计。以下是步骤。在您的项目中创建一个单独的组件,并将其命名为“ Loader.js”

import React, { Component } from "react";
import { View } from "react-native";
import Spinner from "react-native-spinkit";

export default Loader = ({ isVisible }) => (
  <View
    style={{
      position: "absolute",
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      alignItems: "center",
      justifyContent: "center",
      backgroundColor: nullBackground ? null : "rgba(0, 0, 0, 0.7)",
      zIndex: addZindex ? 2 : null
    }}
  >
    <Spinner isVisible={isVisible} size={20} type={"Circle"} color={"white"} />
  </View>
);

我已经使用Spinner作为指示。您可以改用activityIndi​​cator。现在在app.js(或您的应用程序的根类)中导入它,并在render中使用它

 import Loader from "../Loader";
 render() {
     const { HUD } = this.props;
     return(
       <Loader isVisible={HUD} /> 
     )}

此HUD是商店中维护的状态

export const showHUD = () => {
  return { type: "SHOW_HUD" };
};

export const hideHUD = () => {
  return { type: "HIDE_HUD" };
};
export const sendPlayerID = id => async dispatch => {
  let payload = { user: { one_signal_id: id } };
  dispatch(showHUD());
  const { data } = await axios.put(api.profile(), payload);
  dispatch(hideHUD());
};

因此流程将是这样的。每次您要发送请求。您将调度showHUD,这将使store = true中的HU​​D状态。然后App.js的render函数将再次运行。并在任何屏幕,因为它是绝对的并且具有更高的索引。类似地,一旦您接收到数据,然后调度hideHUD。这将隐藏加载程序。您可以从应用程序中的任何位置显示和隐藏HUD,因为这是一个操作,然后将更新状态。


0
投票

尝试一下,它易于使用的全局检查文档以获取更多信息https://github.com/AlishahSolanki/react-native-globalspinner

© www.soinside.com 2019 - 2024. All rights reserved.