我使用 react native 和 axios 来调用 HTTP 请求。我为显示微调器所做的是在调用我的 HTTP 请求之前将组件状态中的 isLoading 设置为 true,并且在获取数据或发生错误后将其设置为 false。然后我有一个微调组件并根据 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 状态为 store=true。然后 App.js 的渲染功能将再次运行。并在你的任何屏幕上方显示 HUD,因为它是绝对的并且具有更高的索引。类似地,一旦您收到数据。然后调度 hideHUD。这将隐藏加载程序。您可以从应用程序中的任何点显示和隐藏 HUD。因为它是一个会更新状态的操作。
关于react-native - 使用 axios 在 react-native 中添加全局微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211568/