react-native - 使用 axios 在 react-native 中添加全局微调器
问题描述
我正在使用 react native 和 axios 来调用 HTTP 请求。在调用我的 HTTP 请求之前以及在获取数据或发生错误之后将其设置为 false,我为显示微调器所做的操作是在我的组件状态中将 isLoading 设置为 true。然后我有一个微调器组件并根据 isLoading 值显示它......
是否可以在我的所有组件中拥有不需要上述内容的全局微调器?
我认为 axios 中的拦截器可以帮助解决这个问题吗?
解决方案
有可用的软件包,但我建议以您自己的方式设计。以下是步骤。在您的项目中创建一个单独的组件并将其命名为“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 作为指示。您可以使用 activityIndicator 代替。现在在 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。因为它是一个随后将更新状态的操作。
推荐阅读
- postgresql - 如何加快来自 pgbouncer 的 PostgreSQL 连接?(获得连接构成约 80% 的延迟)
- postman - 纽曼:填充堆内存错误。从长远来看
- oracle - PL/SQL 函数返回最小数
- android - 如何使用 android 在 iroha 上授予权限?
- ksh - 删除早于当天开始的文件
- sql-server - 从 DB2 中的表更新 DB1 的表时,找不到多部分标识符错误
- r - 在条形图中使用离散颜色映射,并在 R 中的箱形图上使用抖动
- javascript - 如何在 Typescript 中推送数组中的元素
- ssl - 尝试使用 2 路 SSL 建立 Kafka 但出现错误
- android - 自定义通知 RemoteView 在向左或向右滑动时关闭