使用异步数据获取的服务器端呈现
Server side rendering with async data fetch
我们正在使用 react/react-router/redux
构建我们的网站
我们希望服务器端呈现我们的页面,这些页面应该由我们的数据源中的数据填充。此事务必须是异步的,不幸的是,由于我们想要服务器端呈现,我们不能使用 "componentDidMount" 函数。
在服务器端渲染部分的 redux 教程页面 here,建议:
If you use something like React Router, you might also want to express
your data fetching dependencies as static fetchData() methods on your
route handler components. They may return async actions, so that your
handleRender function can match the route to the route handler
component classes, dispatch fetchData() result for each of them, and
render only after the Promises have resolved. This way the specific
API calls required for different routes are colocated with the route
handler component definitions. You can also use the same technique on
the client side to prevent the router from switching the page until
its data has been loaded.
这是目前我们处理数据获取的方式。我个人不喜欢这种方法,它看起来很笨拙,而且与路由库的耦合度太高。有没有更好的方法 - 希望使用标准 react/router/redux 组件?
在一般情况下,类似于静态 fetchData()
方法的方法是使用 React Router 处理数据获取的正确方法,尽管它可以根据需要深入到子组件(例如 Relay 的工作方式)。
你想这样做的原因是 React Router 一次解析所有匹配的路由。鉴于此,您可以 运行 同时为所有路由处理程序获取数据。
如果相反,您将数据获取绑定到组件上的实例级处理程序,您最终总会遇到获取瀑布,其中组件无法获取其所需数据,直到其所有父级都收到所需数据,等等向前。虽然这在服务器上可能不是什么大问题,但在客户端上却非常不理想。
如果您真的想将数据依赖项并置到组件,您可以考虑使用 React Resolver 之类的东西,但这很容易导致用户体验欠佳。
我们正在使用 react/react-router/redux
构建我们的网站我们希望服务器端呈现我们的页面,这些页面应该由我们的数据源中的数据填充。此事务必须是异步的,不幸的是,由于我们想要服务器端呈现,我们不能使用 "componentDidMount" 函数。
在服务器端渲染部分的 redux 教程页面 here,建议:
If you use something like React Router, you might also want to express your data fetching dependencies as static fetchData() methods on your route handler components. They may return async actions, so that your handleRender function can match the route to the route handler component classes, dispatch fetchData() result for each of them, and render only after the Promises have resolved. This way the specific API calls required for different routes are colocated with the route handler component definitions. You can also use the same technique on the client side to prevent the router from switching the page until its data has been loaded.
这是目前我们处理数据获取的方式。我个人不喜欢这种方法,它看起来很笨拙,而且与路由库的耦合度太高。有没有更好的方法 - 希望使用标准 react/router/redux 组件?
在一般情况下,类似于静态 fetchData()
方法的方法是使用 React Router 处理数据获取的正确方法,尽管它可以根据需要深入到子组件(例如 Relay 的工作方式)。
你想这样做的原因是 React Router 一次解析所有匹配的路由。鉴于此,您可以 运行 同时为所有路由处理程序获取数据。
如果相反,您将数据获取绑定到组件上的实例级处理程序,您最终总会遇到获取瀑布,其中组件无法获取其所需数据,直到其所有父级都收到所需数据,等等向前。虽然这在服务器上可能不是什么大问题,但在客户端上却非常不理想。
如果您真的想将数据依赖项并置到组件,您可以考虑使用 React Resolver 之类的东西,但这很容易导致用户体验欠佳。