前端文章收集

dva-loading插件

2018-11-10  本文已影响652人  林ze宏

说明

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

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);



说明:

异步请求,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'];

上一篇下一篇

猜你喜欢

热点阅读