Skip to content
{}

进阶知识 - redux-thunk

异步提交action

React提供一个异步修改中间件的方式 使用插件 redux-thunk 可以异步修改action

  • 安装 : npm install redux-thunk

  • applyMiddleware : 可以支持注册一些第三方的插件库来写异步的action

createStore(Reducer, applyMiddleware(插件))

  • action :注册完redux-thunk插件会,异步提交action的话内部需要返回一个回调函数,回调函数里面有个形参dispatch函数,异步请求需要在action里面写,在需要调用处理action的时候,使用形参dispatch就可以实现异步调用啦

Store.dispatch((dispatch)=>{dispatch({})})

/News.jsx
import React, { useEffect, useState } from "react";
// 导出全局状态仓库
import Store from "../../Redux/store";
// 导入发布操作事件
import { TabbleHide, TabbleShow, NewList } from "../../Redux/Action";
export default function News(props) {
  // 进入隐藏底部栏 离开显示底部栏
  const [newList, setnewList] = useState(Store.getState().NewReducers.newList);
  useEffect(() => {
    // 如果没有列表数据 就去Action任务里面调用接口异步拿到数据
    if (Store.getState().NewReducers.newList.length === 0) {
      // 调用异步action
      Store.dispatch(NewList());
    } else {
      console.log("Store有数据");
    }
    return () => {
      Store.dispatch(TabbleShow()); //组件销毁 显示
    };
  }, []);

  // 内部需要自己订阅 来接收数据
  Store.subscribe(() => {
    console.log(Store.getState().NewReducers.newList);
    setnewList(Store.getState().NewReducers.newList);
  });
  return (
    <div>
      News
      {/* <div>{props.location.query.id}</div> */}
      {newList.map((item) => {
        return <div key={item.id}>{item.videoName}</div>;
      })}
    </div>
  );
}

<!-- /Redux/Action -->
export const NewList = () => {
  // 异步请求方法在这里写  需要返回一个回调函数 里面形参dispatch可以调用修改action 
  return (dispatch) => {
    axios
      .get(
        "/api/mmdb/movie/v3/list/hot.json?ct=%E9%B9%A4%E5%A3%81&ci=239&channelId=4"
      )
      .then((res) => {
        dispatch({ type: "Newlist", newList: res.data.data.hot });
      });
  };
};


<!-- store.jsx -->
import {
  applyMiddleware,
  legacy_createStore as createStore,
  combineReducers,
} from "redux";
import Thunk from "redux-thunk";

const Reducer = combineReducers({
  TabbleReducer,
  AddReducer,
  NewReducers,
});

// 创建全局状态仓库对象
const Store = createStore(Reducer, applyMiddleware(Thunk)); //applyMiddleware()可以注册支持一些第三方的库来写异步action

export default Store;

好好加油吧,少年!