umi3 使用 dva 的正确姿势

啥也不要配置,直接就内置了,就可以使用了

umi3 使用 dva 的正确姿势_第1张图片

1, 我们先看模型

count.js


function asyncInit() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(100);
        }, 1000);
    });
}
export default {
    namespace: "count", // 可省略
    state: JSON.parse(localStorage.getItem("count")) || 99, // 初始状态:缓存或空数组

    effects: {
        // generactor 这玩意还再用,我也是醉了
        //这个执行异步操作,这玩意是* 生成器函数??
        * init(action, { call, put }) {
            let payload = yield call(asyncInit);
            yield put({ type: "setCount", payload });
        }

    },
    reducers: {
        add(state, action) {
            return state + action.payload;
        },
        minus(state, action) {
            return state - action.payload;
        },
        setCount(state, action) {
            state = action.payload;
            return state;
        }

    }
};

2, 我们再看界面:

hello.js

import React from 'react';
import styles from './Hello.css';
import { connect } from 'dva'
import { Button } from 'antd'


const hello = (props) => {
  const { count, add, init } = props;
  return (
    

Page Hello

{count}

& nbsp;& nbsp;
) } const mapStatetoprops = state => ({ count: state.count }); const actionCreater = { add: (payload) => ({ type: "count/add", payload }), minus: (payload) => ({ type: "count/minus", payload }), init: (payload) => { return { type: "count/init", payload } } } export default connect(mapStatetoprops, actionCreater)(hello);

我能说啥,是不是很简单,

具体使用和redux 差不多,无非多命名空间

你可能感兴趣的:(react)