Redux Thunk操作,axios返回多个值

问题描述 投票:0回答:1

我有一个React应用,我正在使用Redux-Thunk和adios来获取API,该操作成功触发,但是它返回多个有效负载,这意味着它多次触发,如何使其仅触发一次代码

动作

import Axios from "axios";
import { fetchEnglishLeagueTable } from "./ActionTypes";

export function fetchEnglishTable() {
  var url = "https://api.football-data.org/v2/competitions/PL/matches";
  var token = "52c8d88969d84ac9b17edb956eea33af";
  var obj = {
    headers: { "X-Auth-Token": token }
  };
  return dispatch => {
    return Axios.get(url, obj)
      .then(res => {
        dispatch({
          type: fetchEnglishLeagueTable,
          payload: res.data
        });
      })
      .catch(e => {
        console.log("Cant fetch ", e);
      });
  };
}

减速器

import { fetchEnglishLeagueTable } from "../actions/ActionTypes";
const initialState = {
  EnglishTable: {}
};

const rootReducer = (state = initialState, action) => {
  switch (action.type) {
    case fetchEnglishLeagueTable:
      return {
        ...state,
        EnglishTable: action.payload
      };
    default:
      return state;
  }
};

export default rootReducer;

const League = props => {
  useEffect(() => {
    props.getLeagueTable();
  }, [props.leagueTable]);
  console.log(props.leagueTable);
  return <p>ihi</p>;
};
const mapStateToProps = state => ({
  leagueTable: state.EnglishTable
});
const mapDispatchToProps = dispatch => {
  return { getLeagueTable: () => dispatch(fetchEnglishTable()) };
};

export default connect(mapStateToProps, mapDispatchToProps)(League);

商店

import rootReducer from "./Reducer";
import thunk from "redux-thunk";

const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;

这里是它返回的内容Multiple Action firing

reactjs redux react-redux axios redux-thunk
1个回答
0
投票
只需从leagueTable的依赖项数组中删除useEffect,因此仅在安装组件后才将其提取。因为现在您有一个循环:

[获取联赛-> LeagueTable更新-> useEffect看到leagueTable在依赖项数组中发生了更改,并再次调用以获取联赛,我们有了一个循环。

const League = props => { useEffect(() => { props.getLeagueTable(); }, []); // <~ no props.leagueTable here console.log(props.leagueTable); return <p>ihi</p>; };

希望有帮助:)
© www.soinside.com 2019 - 2024. All rights reserved.