首页 > 解决方案 > 使用 axios 在 react-native 中添加全局微调器

问题描述

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

标签: react-nativespinnerloadingreact-navigationinterceptor

解决方案


有可用的软件包,但我建议以您自己的方式设计。以下是步骤。在您的项目中创建一个单独的组件并将其命名为“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(或你的应用程序的根类)中导入它并在渲染中使用它

 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 这将使商店中的 HUD 状态 = true。然后 App.js 的渲染功能将再次运行。并在您的任何屏幕上方显示 HUD,因为它是绝对的并且具有更高的索引。类似地,一旦您收到数据。然后调度 hideHUD。然后将隐藏加载程序。您可以从应用程序中的任何点显示和隐藏 HUD。因为它是一个随后将更新状态的操作。


推荐阅读