从网络获取数据时如何隐藏和显示进度条?

How to hide and show progress bar when fetching data from network?

我在 ReactNative 应用程序中使用 Context Api 和 Hooks

这是我从 api

中获取博客数组的代码
const getBlogPosts = dispatch => {
  return async () => {
    try {
      const response = await jsonServer.get("/blogposts");
      dispatch({ type: "get_blogposts", payload: response.data });
    } catch (err) {
      dispatch({
        type: "get_blogposts",
        payload: "Something went wrong"
      });
    }
  };
};

const blogReducer = (state, action) => {
  switch (action.type) {
    case "get_blogposts":
      return action.payload;
     .....

这是我的组件文件,我正在做类似下面的事情

const IndexScreen = ({ navigation }) => {
  const { state, getBlogPosts } = useContext(Context);

  useEffect(() => {
    getBlogPosts();

  }, []);

  return (
    <View>
      <FlatList..../>
      {state.length === 0 ? <ProgressBar /> : null}

假设没有博客那么网络操作完成后进度条一直显示所以我无法编写上面显示和显示进度条的代码 现在,我尝试在用户调用 getBlogPosts 时触发多个分派,但这会将状态值从布尔值更改为数组,然后再次更改为布尔值。

有没有简单的方法来处理进度条的可见性?

由于您的博客数组可以为空,加载后您的博客数组可能相同。您将必须存储一个布尔值,指示加载已在您所在的州完成。

获取数据后,只需将此值设置为 false :

const IndexScreen = ({ navigation }) => {
  const { state, getBlogPosts } = useContext(Context);
  const [loading, setLoading] = useState(true);

  useEffect(async () => {
    await getBlogPosts();
    setLoading(false)
  }, []);

  return (
    <View>
      <FlatList..../>
      {loading && <ProgressBar />}

您还必须制作效果 async 才能使用 await

我还使用内联 if (&&) 来渲染加载组件。

如果调度是 get_blogposts_in_progress 和调度 [=16],你可以在调度中有一个新类型,如 get_blogposts_in_progress,并在减速器中设置 true/false,如 state.loading = true =] 当 api 调用成功或出错时。

const getBlogPosts = dispatch => {
  return async () => {
    dispatch({ type: "get_blogposts_in_progress" });
    try {
      const response = await jsonServer.get("/blogposts");
      dispatch({ type: "get_blogposts", payload: response.data });
    } catch (err) {
      dispatch({
        type: "get_blogposts",
        payload: "Something went wrong"
      });
    }
  };
};
const blogReducer = (state, action) => {
  switch (action.type) {
    case "get_blogposts_in_progress":
      return { ...state, ...{ loading: true } };
    case "get_blogposts":
      return { ...action.payload, ...{ loading: false } };
     .....

和组件文件。

const IndexScreen = ({ navigation }) => {
  const { state, getBlogPosts } = useContext(Context);

  useEffect(() => {
    getBlogPosts();

  }, []);

  return (
    <View>
      <FlatList..../>
      {state.loading ? <ProgressBar /> : null}