React-redux之异步action的使用方法

2022-02-19  本文已影响0人  网恋被骗二块二

之前的 react-redux基础用法 中基本是同步的修改 redux 中的 state 数据,今天补充如何进行异步操作。

首先安装 thunk 和 logger 两个 redux 的插件

$ npm i redux-thunk
$ npm i redux-logger

结合上一篇文章的内容,此时我们已经有了以下文件目录

src 
| -- api
| -- | -- api.js
| -- | -- user.js
| -- store
| -- | -- index.js
| -- reducers
| -- | -- user.js
| -- | -- index.js
| -- action
| -- | -- constants.js
| -- | -- user.js
| -- index.js
| -- app.js

这里由于项目的关系我直接使用用户登录这一模块来作为案例。
那么按照之前的思路一步步来——

  1. 创建 store 需要使用到
import { createStore } from 'react-redux'
// 结合异步操作需要额外使用到 applyMiddleware 方法
import { applyMiddleware } form 'react-redux'
// 再将之前安装的两个 redux 插件引入
import thunk from 'redux-thunk'
import logger from 'redux-logger'
// 引入合并好的 reducers
import reducers from '../'

// 历史版本 
// const store = createStore(rootReducer)
// 结合插件,创建一个 store 实例
const store = createStore(rootReducer, applyMiddleware(thunk, logger))

export default store
  1. 设置 reducers
import { USER_LOGIN_SUCCESS, USER_RESET } from '../actions/constants'

import _ from 'lodash'

const initialState = {
  info: null,
  token: null,
}

/**
 * 用于同步更新与用户登录状态相关的状态数据
 * state 更新前的旧状态
 * action 普通对象,描述如何更新状态,有 type 和 payload 属性
 * @return 返回更新后的状态
 */

export default (state = initialState, { type, payload }) => {
  // 对原 state 实行深拷贝
  const copy = _.cloneDeep(initialState)

  switch (type) {

  case USER_LOGIN_SUCCESS: // 登陆成功
    copy.info = payload.info
    copy.token = payload.token
    return copy

  case USER_RESET:
    copy.info = null,
    copy.token = null
    return copy

  default:
    return state
  }
}
  1. action.js
    鉴于 constants.js 只是对于判断常量的存储,所以不过多展示
    按照之前的思路,对于用户是否登录成功,这里一般有两种判断
export const loginSuccessAction = (user) => ({
  type: USER_LOGIN_SUCCESS,
  payload: user,
})
export const userResetAction = (user) => ({
  type: USER_RESET,
})

但是在页面的使用中并不是直接使用了,既然讲出来了,肯定是要结合 axios 请求一起操作。所以在下方

 * 定义异步 Action 创建函数,在 action creator 中也可以返回一个函数
 * 该返回的函数会自动被 redux-thunk 中间件调用执行。在 thunk 中间件
 * 调用返回函数执行时,会传递 dispatch 参数
// 引入 api 目录下 user.js 文件中与登录相关的 loginAsync 函数
import { loginAsync } from '../api/user'

// 重新定义一个函数,函数中返回一个回调函数
// 这个回调函数的参数是 dispatch,用于调用定义的 action 方法
export const loginAsyncAction = (user) => (dispatch) => {
  // 这里用了 ant desgin 的组件,各需所求
  loginAsync(user)
    .then((data) => {
      // 如果没有查询到匹配用户
      if (data.length === 0) {
        // 提示
        notification['error']({
          message: '登录错误',
          description:
              '请输入正确的账户或密码.',
        })
        // 调用 用户重置
        dispatch({
          type: USER_RESET,
        })
      } else {
        // 提取 姓名 token 和 id
        const res = {
          info: data[0].name,
          token: data[0].token,
        }
        localStorage.setItem('loginInfo', JSON.stringify(res))
        dispatch(loginSuccessAction(res))
      }
    })
}

基本新增的东西就只有这些了,需要在哪些组件使用就用 connect 方法映射一下。
另外记得

如果 mapStateToProps 不需要参数只能给 null
然后 hoc 成下面的写法,不然会报错的
connect(mapStateToProps, mapDispatchToProps)(Login)
上一篇 下一篇

猜你喜欢

热点阅读