Skip to content
{}

进阶知识 - redux-promise

redux-promise

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

  • 安装 : npm install redux-promise

  • applyMiddleware : 可以支持注册一些第三方的插件库来写异步的action> React提供一个异步修改中间件的方式 使用插件 redux-promise 可以异步修改action

createStore(Reducer, applyMiddleware(插件))

  • 安装 : npm install redux-promise

  • action :注册完redux-promise插件,异步提交action的话内部需要 返回一个promise对象就可以啦,在异步请求里面直接return action任务

<!-- 写法一  返回一个promise对象-->
Stort.subscribe( 
    return new Promise((resolve,reject)=>{
         resolve('1') 
    })
    .then(()=>{
    <!-- action任务 -->
    return {
        type:"newlist",
        value:''
    }
}))

<!-- 写法二 async await 返回action对象-->
Stort.subscribe( (async()=>{
    const list = await axios
    .get(
      "/api/mmdb/movie/v3/list/hot.json?ct=%E9%B9%A4%E5%A3%81&ci=239&channelId=4"
    )
    .then((res) => {
      return { type: "Newlist", newList: res.data.data.hot };
    });
  return list;
})())

示例

/News.jsx
import React, { useEffect, useState } from "react";
import Store from "../../Redux/store";
import { TabbleHide, TabbleShow, NewList2 } 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(NewList2());
    } else {
      console.log("Store有数据");
    }
    return () => {
      Store.dispatch(TabbleShow()); //组件销毁 显示
    };
  }, []);

  // 内部需要自己订阅 来接收数据
  Store.subscribe(() => {
    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 -->
// redux-promise写法
// 返回一个promise对象就可以啦  源码内部会调用then方法 最终拿到一个对象
export const NewList2 = async () => {
  // 异步请求方法在这里写
  return axios
    .get(
      "/api/mmdb/movie/v3/list/hot.json?ct=%E9%B9%A4%E5%A3%81&ci=239&channelId=4"
    )
    .then((res) => {
      return { type: "Newlist", newList: res.data.data.hot };
    });
};

// redux-promise async await写法
export const NewList3 = async () => {
  // 异步请求方法在这里写
  const list = await axios
    .get(
      "/api/mmdb/movie/v3/list/hot.json?ct=%E9%B9%A4%E5%A3%81&ci=239&channelId=4"
    )
    .then((res) => {
      return { type: "Newlist", newList: res.data.data.hot };
    });
  return list;
};



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

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

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

export default Store;

好好加油吧,少年!