前言
日常积累,欢迎指正
1、安装依赖
yarn add dva-loading
# or
npm install dev-loading
2、dva-loading 引入
import createLoading from 'dva-loading'
app.use(createLoading())
3、dva-loading 使用 - 利用 dva-loading 实现 loading
3.1、使用 app.use(createLoading()) 之后 reducer 的 state 中会增加一个 loading 属性
3.2、在需要使用 loading 的组件中获取到它
我这里是通过容器组件中将这个 loading 属性传递给需要使用它的组件中的
function mapStateToProps(state, ownProps) {
// console.log(state)
return {
loading:state.loading
}
}
3.3、组件拿到 loading 属性后通过它可以检测指定的异步请求的状态以此来判断对应组件的 loading 状态
这里以异步请求 addAsync 为例
3.3.1、model 代码
import { listStatus,actionType } from '../constants/todoList'
import { asyncAdd } from '../services/todoList'
export const todoList = 'todoList'
export default {
namespace: todoList,
reducers: {
ADD(state, action) {
return [
...state,
{
id: action.id,
text: action.text,
status: action.status
}
]
}
},
effects: {
*addAsync(action, effects) {
const result = yield effects.call(asyncAdd, action.text)
// console.log(result)
yield effects.put({
type:`${todoList}/ADD`,
id: action.id,
text: result,
status: action.status
})
}
}
};
3.3.2、需要使用 loading 属性的组件
import { Spin } from 'antd'
export default class TodoList extends React.Component {
render() {
const loading = this.props.loading.effects['todoList/addAsync']
return (
<Spin spinning={!!loading}>
<div>
<h1>todoList</h1>
</div>
</Spin>
)
}
}
注意点: loading.effects['todoList/addAsync'] 的 key 值
这里 loading.effects[‘todoList/addAsync’] 就会拿到 namespace 为 ‘todoList’ 的 model 中的名称为 addAsync 的异步请求的状态(true/false),当指定的异步请求不存在就会返回 undefined

本文详细介绍了如何使用 dva-loading 实现页面加载状态管理。首先,介绍了安装和引入 dva-loading 的步骤,然后讲解了如何在 reducer 中添加 loading 属性,并在组件中获取和使用该属性来跟踪异步请求状态。通过具体示例,包括 model 代码和使用 loading 属性的组件,展示了如何利用 loading.effects 监测特定异步操作的 loading 状态。
1230

被折叠的 条评论
为什么被折叠?



