在简单版本的基础上完善并规范化一些操作。
1.创建常量文件,统一规范
//新建 constant.js
export const INCREMENT = "increment";
export const DECREMENT = "decrement";
在action.js 和 reducer.js 中都引入 常量。
2.规范化操作action
// 之前都是在组件中调用dispatch
const increment = ()=>{
store.dispatch({type:'increment',data:'xxx'})
},
这样每次都得来写action。现在把action统一规范到文件中。
新建 count_action.js
import { INCREMENT, DECREMENT } from "./constant";
export const createIncrementAction = (data) => ({
type: INCREMENT,
data,
});
export const createDecrementAction = (data) => ({
type: DECREMENT,
data,
});
组件中引入
import {
createIncrementAction,
createDecrementAction,
} from "../../redux/count_action";
// 直接使用
const increment = () => {
store.dispatch(createIncrementAction(selectValue));
};
const decrement = () => {
store.dispatch(createDecrementAction(selectValue));
};
异步action 和同步action
根据action的类型来进行判断,若action 为一个 Object对象,则为同步。
若 action 为一个函数,则为异步。
使用 redux-thunk中间件来处理异步action
npm i redux-thunk
// store.js
// 引入createStore
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk"; // 引入thunk
import countReducer from "./count_reducer";
export default createStore(countReducer, applyMiddleware(thunk));
// count_action.js
import { INCREMENT, DECREMENT } from "./constant";
export const createIncrementAction = (data) => ({
type: INCREMENT,
data,
});
export const createDecrementAction = (data) => ({
type: DECREMENT,
data,
});
//此处就是异步action 返回一个函数,在返回的函数中写异步操作就行
export const createIncrementAsync = (data, time) => {
return (dispatch) => {
setTimeout(() => {
dispatch(createIncrementAction(data));
}, time);
};
};