我有一个带有asp.netcore后端的简单react redux应用程序。我想在加载数据之前使用类似旋转器等的加载指示器或图标来显示。我的组件是Courses.jsx
import React, { useState, useEffect } from "react";
import {useDispatch,useSelector} from 'react-redux';
import CourseList from "./CourseList" ;
import * as actions from "../_actions/courseActions";
const Courses =(props)=> {
const [loading, setLoading] = useState(true);
const dispatch = useDispatch();
let course = useSelector(state => state.course.list);
const courseList = course.sort((a, b) =>a.updatedOn.localeCompare(b.updatedOn));
useEffect(() => {
dispatch(actions.fetchAll())
}, [])
return(
<div>
{courseList.loading && <em>Loading ...</em>}
<CourseList
courseList={courseList}
/> </div>
);
}
export default Courses;
以下是fetchall的操作courseActions.js
import courseApi from "../_services/courseApi";
import { ACTION_TYPES } from '../_constants';
const formateData = data => ({
...data,
// age: parseInt(data.age ? data.age : 0)
})
export const fetchAll = () => dispatch => {
courseApi.course().fetchAll()
.then(response => {
dispatch({
type: ACTION_TYPES.FETCH_ALL,
payload: response.data
})
}
)
.catch(err => console.log(err))
}
这是courseReducer
import { ACTION_TYPES } from '../_constants';
const initialState = {
list: []
}
export const course=(state = initialState, action)=>{
switch (action.type) {
case ACTION_TYPES.FETCH_ALL:
return {
...state,
list: [...action.payload]
}
// remaining switch cases for simplicity
}
}
我尝试了很多选择,但没有找到任何简单有用的解决方案。我试图在组件中设置loading和setLoading,但在这几行中courseList变得未定义。let course = useSelector(state => state.course.list); const courseList = course.sort((a, b) =>a.updatedOn.localeCompare(b.updatedOn));
我在应用程序中使用了素材ui,所以图标带有素材ui或简单加载。。。或者简单的图像将被欣赏
您需要在返回语句中使用三元运算符。
return(
<div>
{loading === true ? (<h1>Loading...</h1>) : (<CourseList courseList={courseList}/>)}
</div>
);
你需要确保的另一件事是在你的效果中的fetch调用之后更新setLoading(false(,否则";正在加载"永远不会消失。我可以自由输入这个让我知道如果它不起作用&我将在编辑器中编写代码。
如果你愿意,你可以在材料ui进度组件中进行细分,而不是加载。。。我在示例中输入的文本如下:https://material-ui.com/components/progress/