调度执行 AJAX 请求的操作时无限循环 - ReactJS、Redux、Redux-saga

Infinite loop when dispatching action that performs an AJAX request - ReactJS, Redux, Redux-saga

我正在尝试使用 redux-saga 和 axios 为组件加载数据,但我一直遇到无限循环。这些是相关组件:

App.js

class App extends React.Component {
  render() {
    return (
      <div className="app">
        <header>
          <div className="pure-u-1 pure-u-sm-1-3">

          </div>
          <nav className="pure-u-1 pure-u-sm-2-3">
            <ul>
              <li><Link to="/meal-plans">Meal Plans</Link></li>
            </ul>
          </nav>
        </header>
        <main>
          <div className="view-area">
            <Switch>
              <Route exact path="/" component={() => <DashBoard {...this.props} />} />
              <Route exact path="/meal-plans" component={() => <MealPlansContainer {...this.props} />} />
              <Route path="/meal-plans/:id" component={props => <MealPlan {...this.props} {...props} />} />
            </Switch>
          </div>
        </main>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    app: state.app,
    mealPlan: state.mealPlan,
    mealPlans: state.mealPlans,
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

App = withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

export default App;

MealPlan.js

class MealPlan extends React.Component {
    componentDidMount() {
        let id = this.props.match.params.id
        this.props.fetchMealPlan(id);
    }
    render() {
        return (
            <div className="meal-plan pure-g box">
                <div className="pure-u-1">
                    <p>Future Meal Plan Page</p>
                    <LoadingSpinner show={true} />
                </div>
            </div>
        );
    }
}

我是 React 的新手,我对组件生命周期不太了解,但我相信每次 AJAX 请求完成和 'FETCH_MEAL_PLAN_SUCCESSFUL' case 在减速器中运行。

actionCreators.js

export function fetchMealPlan(id) {
  return {
    type: 'FETCH_MEAL_PLAN',
    id
  }
}

export function fetchMealPlanSuccessful(data) {
  return {
    type: 'FETCH_MEAL_PLAN_SUCCESSFUL',
    data
  }
}

export function fetchMealPlanFail(message) {
  return {
    type: 'FETCH_MEAL_PLAN_FAIL',
    message
  }
}

sagas.js

function* fetchMealPlan(action) {
  try {
    const mealPlan = yield call(api.get, '/meal_plans/' + action.id);
    yield put(fetchMealPlanSuccessful(mealPlan.data));
  } catch (e) {
    yield put(fetchMealPlanFail(e.message));
  }
}

function* watchFetchMealPlan() {
  yield takeLatest('FETCH_MEAL_PLAN', fetchMealPlan);
}

mealPlan.js(减速器)

function mealPlan(state = {}, action) {
  switch(action.type) {
    case 'FETCH_MEAL_PLAN':
      return state;
    case 'FETCH_MEAL_PLAN_FAIL':
      return state;
    case 'FETCH_MEAL_PLAN_SUCCESSFUL':
      state = Object.assign({}, action.data);
      return state;
      break;
    default:
      return state;
  }
}

export default mealPlan;

如果我不停止该应用程序,它将继续发出请求。在此测试中,它发出了 4,200 多个请求: App in an infinite loop

我花了几个小时研究如何在更改路线后从我的 API 为组件最好地加载数据,但到目前为止我一直没有成功。预先感谢您的帮助。

通常一个组件应该 运行 componentDidMount 一次,除非它被释放然后再次安装。如果它的道具或状态改变,那么 componentDidUpdate 将被解雇。

所以如果你遇到多个 componentDidMount,那么这个组件很可能嵌套为 child(我猜你是从你的代码片段中做的),然后当它 parent的(App)状态或道具发生变化,这将re-render其children(包括MealPlan)。因为您正在将 mealPlan & mealPlan 从 redux 连接到 App。每当你调用 API 时,App 的 props 将被更新,从而导致其 children 被 re-rendered,并导致 MealPlan 一次又一次地触发 componentDidMount

我对 React 不是很了解。但是我没有看到你设置路由的方式。一种方法是在单独的文件中定义路由器,然后像这样使用路由器(这是 而不是 使用 react-router 的 code-splitting 功能:

const router = (
  <Router history={browserHistory}>
    <Route path="/" component={App}>
     <Route path="/meal-plans" component={MealPlan} />
    </Route>
  </Router>
)

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}> // react-redux provider
      { router }
    </Provider>,
  document.querySelector('#main'));

如果你想做 code-splitting,因为你正在使用 redux-sagas,一个好的模板是 https://github.com/react-boilerplate/react-boilerplate。看看他们是怎么做的,你就可以实现你想要的