异步 action 学习笔记

这里我们默认你是会 react-redux 的,并且我们只讨论最简单的 怎么用异步action

  1. 首先我们需要安装 redux-thunk
    npm i redux-thunk -S
  2. 在打包js的入口文件例如main.js 中加入
    import thunkMiddleware from 'redux-thunk';
  3. 在创建 store 时,使用以下代码
const store = createStore(rootReducer,
    applyMiddleware(thunkMiddleware));
  1. mapDisPatchToProps 函数中,dispatch()函数发送的不再是一个action对象,而是一个function() 函数,例如:
const mapDispatchToProps = (dispatch) => {
    return {
        onCheckLogin: (mobilePhone, password, capture) => {
            dispatch(isCorrect(mobilePhone, password, capture));
        }
    }
};
  1. 然后 action 中,首先调用 mapDisPatchToProps 中的函数,例如在上例中就是 isCorrect 函数,然后在这个函数中发送异步请求,请求完成回来之后,会再发送一次 dispatch(function()),在这个function()中,会发送一个 action 对象,然后到 reducer 里面, reducer 中会根据** action.type ** 来做相应的数据处理,并更新 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('请重新输入');
                return {
                    status: state.status
                }
            }
    }
    return state;
}
export default reducer;

因为我们现在只是给老师一个帐号和密码看能不能跳转到另一个页面,所以我们还没有在 isCorrect 函数中发送异步请求,大概的过程就是这样。

7 .概念关系图如下:

概念关系图

8 .比 middleware好的地方,就是可以少些很多代码,具体少写了那些代码,请自己体会
9 . github地址:https://github.com/RangelZZZ/teacher-system

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容