触发一个reducers和effects中的方法同名的action情况
如果reducers和effects中的方法同名,则,action不知道要执行reducers还是effects,所以,两个都会执行,而已,很容易会造成死循环。所以,要尽量避免reducers和effects方法同名的情况。

redux-actions库
更好的维护代码,清楚的知道项目中用了多少个action,而不用到处去寻找对应的dispatch。主要利用createAction这个方法。
demo代码
1:action/index.js
注意规范:不同的model action 标识注释。
import { createAction } from 'redux-actions'; // 主要利用createAction这个方法
// counter
export const counterAdd = createAction('counter/add');
export const counterAsayAdd = createAction('counter/asayAdd');
// Products
export const productsDelete = createAction('products/delete');

2:UI Component
import React from 'react';
import { connect } from 'dva';
import { counterAdd, counterAsayAdd } from '../actions';
const Counter = ({ dispatch, counter, counterAdd, counterAsayAdd }) => {
function add() {
// dispatch({
// type: 'counter/add',
// params: {
// id: 1,
// age: 2
// }
// })
const params = {
id: 1,
age: 2
}
counterAdd(params);
}
return (
<div style={{ textAlign: 'center', marginTop: 20 }}>
<button onClick={add}>+</button>
</div>
);
};
// mapStateToProps, mapDispatchToProps
export default connect((state) => ({
counter: state.counter,
}), { counterAdd, counterAsayAdd })(Counter);

3:reducers取值说明:

说明:reducers中方法取action时,参数redux-actions,自动加了payload参数,所以,可以使用解构的写法,如:
reducers: {
'add'(state, { type, payload }) {
console.log('type', type);
console.log('payload', payload);
const newCount = state.count + 1;
const r = state.record > newCount ? state.record : newCount;
localStorage.setItem('record', r);
return {
...state,
count: newCount,
record: r
}
},
},

使用这个库的项目demo
https://github.com/hongzelin/github-stars/blob/master/src/actions/index.js
网友评论