在中间件中获取数据时出现无限循环

时间:2019-09-11 14:45:04

标签: reactjs redux react-redux redux-thunk

我尝试获取数据并将其显示为react组件,但是我的中间件中的fetch调用存在无限循环,并且似乎未分派动作。我的帖子组件没有收到结果。

Action.js:

import { DATA_LOADED } from './../constants/action-types';

export function getData() {
    return {type: DATA_LOADED}
}

中间件:

export function asyncMiddleWare({dispatch}) {
    return function(next) {
        return function (action) {
            if (action.type === DATA_LOADED) {
                return fetch('https://jsonplaceholder.typicode.com/posts')
                .then(response => response.json())
                .then(json => {
                    console.log('---');
                    console.log('infinite calls');
                    console.log('---');
                    dispatch({type:DATA_LOADED, payload: json});
                })
            }
            return next(action);
        }
    }
}

减速器:

    if (action.type === DATA_LOADED) {
        return Object.assign({}, state, {
            articles: state.remoteArticles.concat(action.payload)
        })
    }

和商店

import {createStore, applyMiddleware, compose} from 'redux';
import rootReducer from '../reducers/index';
import {asyncMiddleWare } from "../middleware";
import thunk from "redux-thunk";

const storeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, storeEnhancers(applyMiddleware(asyncMiddleWare, thunk)));

export default store;

我在组件的componentDidMount方法中加载数据:

import React from "react";
import { connect } from "react-redux";
import { getData } from "./js/actions/index";

class Post extends React.Component {

    componentDidMount() {
        this.props.getData();
    }

    render () {
        console.log(this.props.articles);
      return (
      <div className='post'>
          {this.props.articles.map(article => (
              <div className='post'>
                  {article}
              </div>
      ))}
      </div>
      )
    }
  }



  const mapStateToProps = (state) => {
    return {
      articles: state.remoteArticles.slice(0, 10)
    };
  }
export default connect(
    mapStateToProps,
    {getData}
)(Post);

1 个答案:

答案 0 :(得分:0)

如果您查看中间件解析的Promise函数,您会注意到您正在再次调度相同类型(DATA_LOADED)的操作,这导致中间件再次对其进行处理。

看看这种方法

export function asyncMiddleWare({dispatch}) {
    return function(next) {
        return function (action) {
            if (action.type === DATA_LOAD_REQUEST) {
                return fetch('https://jsonplaceholder.typicode.com/posts')
                .then(response => response.json())
                .then(json => {
                    console.log('---');
                    console.log('infinite calls');
                    console.log('---');
                    dispatch({type:DATA_LOAD_SUCCESS, payload: json});
                }, (error) => {
                    dispatch({type:DATA_LOAD_ERROR, payload: error});
                })
            }
            return next(action);
        }
    }
}

您应该将REQUEST,SUCCESS和ERROR调用分开,这样,当您调用这些操作中的每一个时,都不会陷入无限循环。