一文搞懂 redux-thunk 中间件用法

521 阅读1分钟

redux-thunk 中间件发送请求流程

1.先上图

无标题.png

Redux store仅支持同步数据流,使用redux-thunk中间件可以帮助在Redux应用中实现异步

  • 组件里面登录发送请求
  • store/action/login.js发送异步请求
  • store/actionTypes 定义常量 type
  • 获取token存储 store/reducers/login.js 更新视图

2. 发送请求完成登录

  • 点击登录 pages/login/index.js
  
  import {useDispatch} from 'react-redux'
  import { userLogin } from '@/store/actions/login'
  const Login = () => {
    const dispatch = useDispatch()
   const onFinish  = (values)=>{ 
     //表单校验通过后
      console.log(values,111);
      //发请求登录
      dispatch(userLogin(values))
    }
  • store/actionTypes 定义常量

      export const LOGIN = 'LOGIN'
    
  • store/action/login.js
  //发请求
  import request from '@/utils/request'
  import { LOGIN } from '../actionTypes'
  export const userLogin = (formData)=>{
      return async dispatch=>{
          //异步请求
          const res = await request({
              url:'/authorizations',
              method:'POST',
              data:formData
          })
          dispatch({
              type:'LOGIN',
              payload:res.data.token
          })
      }
  }
  • 获取token存储 store/reducers/login.js 更新视图
  import { LOGIN } from "../actionTypes"
  const initValue = {
      token: ''
    }
    export default function login(state = initValue, action) {
      if(action.type === LOGIN){
        return {...state,token:action.payload}
      }
      return state
    }

3. 下面附带赠送redux配置 === 开箱即用

  • store/index.js
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
import rootReducer from './reducers'

const middlewares = composeWithDevTools(applyMiddleware(thunk))
const store = createStore(rootReducer, middlewares)
export default store
  • store/reducers/index.js
import { combineReducers } from 'redux'

import login from './login'

const rootReducer = combineReducers({
  login  //可以添加模块
})

export default rootReducer

  • src/index.js
import { Provider } from 'react-redux'
import store from './store'

ReactDOM.render(
  <Provider store={store}>
  <App />
</Provider>,
  document.getElementById('root')
);