用过redux-thunk
的应该知道,操作相对繁琐一点,dispatch
本只可以出发plain object
。redux-thunk
让dispatch
可以返回一个函数。而redux-promise
在此基础上大大简化了操作。
实现效果
关键逻辑代码
- store/index.js
import { createStore, applyMiddleware } from "redux";
import { combineReducers } from "redux-immutable";
import { thunk } from "redux-thunk";
import { createLogger } from "redux-logger";
import reduxPromise from "redux-promise";
import reducer from "./reducer";
const middleware = [thunk, reduxPromise];
const env = process.env.NODE_ENV;
if (env === "development") {
middleware.push(createLogger({ collapsed: true }));
}
const store = createStore(reducer, applyMiddleware(...middleware));
export default store;
- reucer.js
import { fromJS } from "immutable";
import { delay } from "../../utils";
const initstate = fromJS({
list: [],
count: 100,
});
function storeReducers(state = initstate, action) {
console.log("🚀 ~ storeReducers ~ action:", action);
switch (action.type) {
case "ADD":
return state.updateIn(["count"], (n) => n + action.value);
case "MINUS":
return state.updateIn(["count"], (n) => n - action.value);
default:
return state;
}
}
export async function handleAdd() {
await delay(2000);
const data = await Promise.resolve(20);
return { type: "ADD", value: data };
}
export async function handleMinus() {
await delay(2000);
const data = await Promise.resolve(20);
return { type: "MINUS", value: data };
}
export default storeReducers;
可以发现在handleAdd
里面写异步业务获取返回数据是可以正常执行的,功能完好。
当我们注释掉redux-promise
中间件的配置好后,页面会立马报错。
import { createStore, applyMiddleware } from "redux";
import { combineReducers } from "redux-immutable";
import { thunk } from "redux-thunk";
import { createLogger } from "redux-logger";
// import reduxPromise from "redux-promise";
import reducer from "./reducer";
// const middleware = [thunk, reduxPromise];
const middleware = [thunk];
const env = process.env.NODE_ENV;
if (env === "development") {
middleware.push(createLogger({ collapsed: true }));
}
const store = createStore(reducer, applyMiddleware(...middleware));
export default store;
- 组件代码
import { Button, Dialog, setDefaultConfig, Space, Toast } from "antd-mobile";
import { http } from "../api/request";
import { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { handleAdd, handleMinus } from "../store/reducer/store";
function Home() {
const count = useSelector((state) => state.getIn(["store", "count"]));
const dispatch = useDispatch();
function handleAddCount() {
dispatch(handleAdd());
}
function handleMinusCount() {
dispatch(handleMinus());
}
return (
<div className="home-box">
<h2>home</h2>
<p>{count}</p>
<Space>
<Button color="primary" onClick={handleAddCount}>
add
</Button>
<Button color="danger" onClick={handleMinusCount}>
minus
</Button>
</Space>
</div>
);
}
export default Home;
参考资料
- https://github.com/redux-utilities/redux-promise