啥也不要配置,直接就内置了,就可以使用了
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 (
<div>
<h1 className={styles.title}>Page Hello</h1>
<p>{count}</p>
<Button onClick={() => { add(100) }}>+</Button> & nbsp;& nbsp;
<Button onClick={() => { init(90) }}>-</Button>
</div >
)
}
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 差不多,无非多命名空间