基本方法

1.获取数据

在组件中通过请求接口获取数据,并通过dispatch方法分发action

  1. componentDidMount(){
  2. axios.get('http://localhost:5000/getList').then(res=>{
  3. const {data}=res
  4. const action = getListAction(data)
  5. store.dispatch(action)
  6. })
  7. }

2.在actionType文件中创建新的action type

  1. export const GET_LIST = "getList";

3.在actionCreators文件中创建新的action

  1. export const getListAction = (data) => ({
  2. type: GET_LIST,
  3. data,
  4. });

4.在reducer文件中处理业务逻辑

  1. if (action.type === GET_LIST) {
  2. let newState = JSON.parse(JSON.stringify(state));
  3. newState.list=action.data.data.List
  4. return newState;
  5. }

使用Redux-thunk中间件

image.png

1.配置redux-thunk

首先,在store中的index文件中 引入redux-thunk ,然后 再在redux引入中加入applyMiddleware和compose 其中compose用来兼容redux-devtools
配置之前👇

  1. import {createStore} from 'redux';
  2. import reducer from '../reducer';
  3. const store = createStore(
  4. reducer,
  5. window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__
  6. )
  7. export default store

配置之后👇

  1. import {createStore,applyMiddleware,compose} from 'redux';
  2. import reducer from './reducer';
  3. import thunk from 'redux-thunk';
  4. const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?
  5. window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}):compose
  6. const enhanser =composeEnhancers(applyMiddleware(thunk))
  7. const store = createStore(
  8. reducer,
  9. enhanser
  10. )
  11. export default store

如果不使用redux-devtools则可如下配置👇

  1. import {createStore,applyMiddleware} from 'redux';
  2. import reducer from './reducer';
  3. import thunk from 'redux-thunk';
  4. const store = createStore(
  5. reducer,
  6. applyMiddleware(thunk)
  7. )
  8. export default store

2.在actionCreators文件中创建新的action

在这个异步action中 我们reture的并不再是一个对象,而是一个函数,函数中传入一个参数dispatch,在函数中请求接口并使用参数的dispatch来分发之前用来处理逻辑的同步action(getListAction),参数中的dispatch可以直接分发到store中

  1. export const getListAction = (data) => ({
  2. type: GET_LIST,
  3. data,
  4. });
  5. export const getTodoList = () => {
  6. return (dispatch) => {
  7. axios.get("http://localhost:5000/getList").then((res) => {
  8. const { data } = res;
  9. const action = getListAction(data);
  10. dispatch(action);
  11. });
  12. };
  13. };

3.在组件中分发异步cation

  1. componentDidMount(){
  2. const action = getTodoList()
  3. store.dispatch(action);
  4. }