redux-thunk,是一个插件,用来解决异步action的问题,作用是判断当前dispatch的类型,如果是一个function,那么会等方法调用完成之后派发,否则就直接派发。
1.创建一个异步的数据。
/**
* @param 异步处理
*/
export const addAsync = (payload) => (dispatch) => {
setTimeout(() => {
dispatch({
type: "APP/ASYNC",
payload,
});
});
};
2.引入数据使用根据type进行判断触发数据改变。
export default function appReducer(state = { count: 1, name: "Demo" }, action) {
// console.log();
switch (action.type) {
case "PLUS":
return {
...state,
count: state.count + action.payload,
name: action.name,
};
case "Test":
return {
...state,
count: state.count + action.payload,
};
case "APP/ASYNC":
return {
...state,
count: state.count + action.payload,
};
// case "APP/ADD":
// return {
// ...state,
// count: state.count + action.payload,
// };
default:
return { ...state };
}
}
3.更改数据变化。
import { addAction, addAsync } from "../store/actions/app";
function Counter(props) {
const s = useSelector((state) => state.list);
console.log(s, "s");
/**
* @useDispatch 可以获取dispatch方法
*/
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch({ type: "PLUS", payload: s.page })}>
{props.count}
</button>
{/* 引入封装好的action */}
<button onClick={() => dispatch(addAction(8))}>{props.count}</button>
<button onClick={() => dispatch(addAsync(3))}>{props.count}</button>
</div>
);
}
4.报错提示:点击第二个button进行数据累加时出现以下问题:
redux.js:275 Uncaught Error: Actions must be plain objects. Instead, the actual type was: 'function'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions.
解决此问题,需要下载redux-thunk插件进行解决。具体解决办法请看如下代码:
需要使用applyMiddleware方法进行解决;
import { createStore, combineReducers, applyMiddleware } from "redux";
import app from "./reducer/app";
import list from "./reducer/list";
import person from "./reducer/person";
import thunk from "redux-thunk";
const rootReducer = combineReducers({ app, list, person });
const store = createStore(rootReducer, applyMiddleware(thunk));
export default store;
------以上方法很老,纯属是自己学习做笔记!!!!