這里我們默認(rèn)你是會(huì) react-redux 的贰盗,并且我們只討論最簡(jiǎn)單的 怎么用異步action
- 首先我們需要安裝
redux-thunk
npm i redux-thunk -S
- 在打包js的入口文件例如
main.js
中加入
import thunkMiddleware from 'redux-thunk';
- 在創(chuàng)建 store 時(shí),使用以下代碼
const store = createStore(rootReducer,
applyMiddleware(thunkMiddleware));
- 在
mapDisPatchToProps
函數(shù)中哺壶,dispatch()
函數(shù)發(fā)送的不再是一個(gè)action
對(duì)象,而是一個(gè)function()
函數(shù)横殴,例如:
const mapDispatchToProps = (dispatch) => {
return {
onCheckLogin: (mobilePhone, password, capture) => {
dispatch(isCorrect(mobilePhone, password, capture));
}
}
};
- 然后
action
中昆禽,首先調(diào)用mapDisPatchToProps
中的函數(shù),例如在上例中就是isCorrect
函數(shù)择卦,然后在這個(gè)函數(shù)中發(fā)送異步請(qǐng)求敲长,請(qǐng)求完成回來(lái)之后,會(huì)再發(fā)送一次dispatch(function())
,在這個(gè)function()
中秉继,會(huì)發(fā)送一個(gè)action
對(duì)象,然后到reducer
里面,reducer
中會(huì)根據(jù)** action.type ** 來(lái)做相應(yīng)的數(shù)據(jù)處理祈噪,并更新 state
** action.js **
'use strict';
export const isCorrect = (mobilePhone, password, capture) = {
return (dispatch) => {
dispatch(checkInfor(mobilePhone, password, capture));
}
};
export const checkInfor = (mobilePhone, password, capture) => {
if (mobilePhone === 'admin@admin.com' && password === '12345678' && capture === '1234') {
return {
type: 'LOGIN',
}
} else {
return {
type: 'ERROR',
}
}
};
** reducer.js **
function reducer(state = {
status: false
}, action) {
switch (action.type) {
case 'LOGIN':
{
return {
status: !state.status
}
}
case 'ERROR':
{
alert('請(qǐng)重新輸入');
return {
status: state.status
}
}
}
return state;
}
export default reducer;
因?yàn)槲覀儸F(xiàn)在只是給老師一個(gè)帳號(hào)和密碼看能不能跳轉(zhuǎn)到另一個(gè)頁(yè)面,所以我們還沒(méi)有在 isCorrect
函數(shù)中發(fā)送異步請(qǐng)求尚辑,大概的過(guò)程就是這樣辑鲤。
7 .概念關(guān)系圖如下:
概念關(guān)系圖
8 .比 middleware好的地方,就是可以少些很多代碼杠茬,具體少寫了那些代碼月褥,請(qǐng)自己體會(huì)
9 . github地址:https://github.com/RangelZZZ/teacher-system