如何在异步调用期间显示加载指示符



//post-thunk.js

import { postActions } from "./post-slice";
export const fetchPostData = () => {
return async (dispatch) => {
const postDataFunc = async () => {
const resPro = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
if (!resPro.ok) {
throw new Error("Error in fetching data!");
}
const resJson = await resPro.json();
return resJson;
};
try {
const postData = await postDataFunc();
dispatch(postActions.replacePostList({ postList: postData || [] }));
} catch (error) {
console.log("Error: ", error);
}
};
};
  • 进行api调用并调度它

//post-lice.js

import { createSlice } from "@reduxjs/toolkit";
const postSlice = createSlice({
name: "postSlice",
initialState: {
postList: [],
},
reducers: {
replacePostList(state, action) {
state.postList = action.payload.postList;
},
},
});
export const postActions = postSlice.actions;
export default postSlice;
  • 创建了一个redux切片,用于定义reducers

//post.js

import { Fragment } from "react";
import { useSelector } from "react-redux";
export default function Posts() {
const storePosts = useSelector((state) => {
return state.postReducer.postList;
});
return (
<Fragment>
{storePosts.map((element) => (
<div key={element.id}>{element.title}</div>
))}
</Fragment>
);
}
  • post.js是一个组件,用于显示"文章标题"列表

我想在<Posts>组件即posts.js中显示一个类似<div>loading ... </div>的加载程序,而数据是在post-shunk.js中获取的,即类似的东西

{ isLoading &&  <div>Loading...</div>}
{ !isLoading && <display post title list>}

但我无法理解,如何识别,何时加载数据,何时完全提取数据,以便将isLoading设置为"true"或"false"。请告诉我方向。

以下是解决方案。

//thunk.js后

import { postActions } from "./post-slice";
export const fetchPostData = () => {
return async (dispatch) => {
const postDataFunc = async () => {
const resPro = await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
if (!resPro.ok) {
throw new Error("Error in fetching data!");
}
const resJson = await resPro.json();
return resJson;
};
try {
const postData = await postDataFunc();
dispatch(postActions.replacePostList({ postList: postData || [] }));
dispatch(postActions.loadingStatus({status: true}))
} catch (error) {
console.log("Error: ", error);
}
};
};

//许可后.js

import { createSlice } from "@reduxjs/toolkit";
const postSlice = createSlice({
name: "postSlice",
initialState: {
postList: [],
loading: false
},
reducers: {
replacePostList(state, action) {
state.postList = action.payload.postList;
},
loadingStatus(state,action){
state.loading = action.payload.status;
}
},
});
export const postActions = postSlice.actions;
export default postSlice;

//post.js

import { Fragment } from "react";
import { useSelector } from "react-redux";
export default function Posts() {
const storePosts = useSelector((state) => {
return state.postReducer.postList;
});
const loadingStatus = useSelector((state) => {
return state.postReducer.loading;
});
return (
<Fragment>
{loadingStatus &&
storePosts.map((element) => (
<div key={element.id}>{element.title}</div>
))}
{!loadingStatus && <div>Loading ...</div>}
</Fragment>
);
}

相关内容

  • 没有找到相关文章

最新更新