带有 axios 返回多个值的 Redux Thunk 操作

Redux Thunk action with axios returning multiple values

我有一个使用 redux-thunkaxios 来获取 API 的 React 应用程序。操作成功触发,但是 returns 多个有效载荷,这意味着它触发了多次。

如何让它只触发一次?

代码

操作

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;

就是这样 returns

只需从 useEffect 的依赖项数组中删除 leagueTable,这样它只会在安装组件后获取它们。因为现在你有一个循环:

Get leagues -> leagueTable updates -> useEffect 发现 leagueTable 在依赖数组中发生了变化,并调用再次获取 leagues 并且我们有一个循环。

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

希望对您有所帮助:)