说明
dva-loading 插件是对异步才作用的;该插件是对reducers新增state数据(loading对象),所以,在页面应该导入对应的数据(也就是loading数据),对其进行操作。
Install
$ npm install dva-loading --save
Usage
import createLoading from 'dva-loading';
const app = dva();
app.use(createLoading(opts));
项目应用实例
src/index.js
UI Component (UserPage)
import React from 'react';
import { connect } from 'dva';
import { userfetch } from '../actions';
const UserPage = (props) => {
console.log(props.loading);
const { userfetch } = props;
function start() {
userfetch();
}
return(
<div>
<button onClick={start}>发送请求</button>
</div>
)
}
const mapStateToProps = (state) => {
console.log(state);
return {
user: state.users,
loading: state.loading
}
}
export default connect(mapStateToProps, { userfetch })(UserPage);
说明:
-
当引入dva-loading插件之后,reducers中的state新增了loading对象,如下图所示,在UI Component打印出结果;
-
loading对象中有三个变量,effects、global、models。
还没有发送异步请求,注意loading对象中三个变量的初始值 -
当发送一个异步请求时,loading值的变化,如下图所示:
分析:
1:请求前,loading为:
laoding: {
effects: {}
global: false
models: {}
}
请求前,global为false,effects和models为空对象
2:请求中,loading为:
loading: {
effects: {users/user/fetch: true}
global: true
models: {users: true}
}
global为true;
effects的key为dispatch的type值,value为true;
models的key为namespace值,value为true;
3:请求完成,loading为:
loading: {
effects: {users/user/fetch: false}
global: false
models: {users: false}
}
global为false;
effects的key为dispatch的type值,value为false;
models的key为namespace值,value为false;
应用实例
import React from 'react';
import { connect } from 'dva';
import { userfetch } from '../actions';
const UserPage = (props) => {
console.log(props.loading);
const { userfetch } = props;
const { error, user } = props.user;
const isFetch = props.loading.effects['users/user/fetch'];
let data = "";
if (isFetch) {
data = '正在加载中。。。'
} else if (user) {
data = user.data[0]['name'];
} else if (error) {
data = error.message;
}
function start() {
userfetch();
}
return(
<div>
<h1>User</h1>
<p>{data}</p>
<p>
<button onClick={start}>发送请求</button>
</p>
</div>
)
}
const mapStateToProps = (state) => {
console.log(state);
return {
user: state.users,
loading: state.loading
}
}
export default connect(mapStateToProps, { userfetch })(UserPage);
重点代码:
const isFetch = props.loading.effects['users/user/fetch'];
- 利用effects,判断局部loading;
- 也可以在项目最上层组件,利用global属性,只要发送异步请求,就展示loading状态;
网友评论