一次响应API次调用多路由设计

React one time API call for multiple routes design

我想说最 "Reacty" 的方法是在顶级组件的 componentWillMount 方法中实现全局 API 调用(例如,AppComponent).现在,您已将它放在一个组件中,该组件将为应用程序的每个子组件安装,防止 API 调用在每次安装时被触发可能很棘手。

使用 HOC 将这些数据提供给应用程序的其他组件是个不错的主意,但它会使您的应用程序更加隐蔽,而且我不认为您获得了很多:您添加具有隐式行为的组件,而不是仅在 mapStateToProps 中添加一行。

在 API 全局 API 调用成功后 触发特定页面 API 调用非常棘手。您将需要一种方法来监视全局 API 调用已解决的事实,并且在 React/Redux 的思维方式中,这意味着调度一个动作。要异步分派操作,您将需要一个 Redux 中间件,例如 redux-thunk or redux-saga (I believe redux-thunk is a lot easier for beginners). Now, if you have a way to know whether or not the global API call is a success, you can wait for a specific action to be dispatched (say, GLOBAL_API_CALL_SUCCESS). Now, this is the part where I'm doing myself a bit of publicity : I've written redux-waitfor-middleware,它允许您等待分派特定操作。如果你使用它,它可能看起来像这样:

export async function fetchComponentSpecificData() {
  await waitForMiddleware.waitFor([GLOBAL_API_CALL_SUCCESS]);

  // perform actual API call for this specific component here
}

我并不是说 waitFor 中间件是实现这一目标的最佳工具,但如果您是新手,它可能是最容易理解的!