异步 action 学习笔记

作者: rangel | 来源:发表于2016-10-22 20:37 被阅读49次

这里我们默认你是会 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

相关文章

网友评论

  • 6d96978eeefb:很棒。有一点需要注意一下,你贴上来的代码最好先到http://jsbeautifier.org/上格式化一下,虽然麻烦一次,但是方便了所有的阅读者
    rangel: @nowind 谢谢老师阅读打赏,还给我提出意见,明天去了就改😀,以后我会更认真的写博客的

本文标题:异步 action 学习笔记

本文链接:https://www.haomeiwen.com/subject/ohlhuttx.html