2

我有一个使用 Redux 和 React Router 的通用 React 应用程序。我的一些路由包含在客户端上将触发 AJAX 请求以混合数据以供显示的参数。在服务器上,这些请求可以同步完成,并在第一个请求时呈现。

我遇到的问题是:当在componentWillMount路由组件上调用任何生命周期方法(例如 )时,调度将在第一次渲染中反映的 Redux 操作已经太晚了。

这是我的服务器端渲染代码的简化视图:

路由.js

export default getRoutes (store) {
  return (
    <Route path='/' component={App}>
      <Route path='foo' component={FooLayout}>
        <Route path='view/:id' component={FooViewContainer} />
      </Route>
    </Route>
  )
}

服务器.js

let store = configureStore()
let routes = getRoutes()
let history = createMemoryHistory(req.path)
let location = req.originalUrl
match({ history, routes, location }, (err, redirectLocation, renderProps) => {
  if (redirectLocation) {
    // redirect
  } else if (err) {
    // 500
  } else if (!renderProps) {
    // 404
  } else {
    let bodyMarkup = ReactDOMServer.renderToString(
      <Provider store={store}>
        <RouterContext {...renderProps} />
      </Provider>)
    res.status(200).send('<!DOCTYPE html>' +
      ReactDOMServer.renderToStaticMarkup(<Html body={bodyMarkup} />))
  }
})

FooViewContainer组件在服务器上构建时,它的第一次渲染的 props 将已经固定。我发送到商店的任何操作都不会反映在第一次调用 中render(),这意味着它们不会反映在页面请求上传递的内容中。

React Router 传递的id参数本身对第一次渲染没有用。我需要同步将该值水合为适当的对象。我应该把这种保湿剂放在哪里?

一种解决方案是将它内联地放在render()方法内部,例如在服务器上调用它。这对我来说显然是不正确的,因为 1)它在语义上没有意义,以及 2)它收集的任何数据都不会正确地发送到商店。

我见过的另一种解决方案是向fetchData路由器链中的每个容器组件添加一个静态方法。例如这样的:

FooViewContainer.js

class FooViewContainer extends React.Component {

  static fetchData (query, params, store, history) {
    store.dispatch(hydrateFoo(loadFooByIdSync(params.id)))
  }

  ...

}

服务器.js

let { query, params } = renderProps
renderProps.components.forEach(comp => 
  if (comp.WrappedComponent && comp.WrappedComponent.fetchData) {
    comp.WrappedComponent.fetchData(query, params, store, history)
  }
})

我觉得必须有比这更好的方法。它不仅看起来相当不优雅(是.WrappedComponent一个可靠的接口吗?),而且它也不适用于高阶组件。如果任何路由组件类被除此之外的任何东西包装,connect()则将停止工作。

我在这里想念什么?

4

2 回答 2

1

我最近写了一篇关于这个需求的文章,但是它确实需要使用 redux-sagas。从 redux-thunks 的角度来看,它确实采用了这种静态 fetchData/need 模式。

https://medium.com/@navgarcha7891/react-server-side-rendering-with-simple-redux-store-hydration-9f77ab66900a

我认为这种传奇方法更清晰,更易于推理,但这可能只是我的看法:)

于 2016-08-01T14:16:50.093 回答
0

似乎没有比fetchData我在原始问题中包含的方法更惯用的方法了。尽管它在我看来仍然不优雅,但它的问题比我最初意识到的要少:

  • .WrappedComponent是一个稳定的接口,但无论如何都不需要引用。Reduxconnect函数自动将原始类中的任何静态方法提升到其包装器中。
  • 包装 Redux 绑定容器的任何其他高阶组件需要提升(或通过)任何静态方法。

我可能没有看到其他注意事项,但我已经在我的server.js文件中确定了这样的辅助方法:

function prefetchComponentData (renderProps, store) {
  let { params, components, location } = renderProps
  components.forEach(componentClass => {
    if (componentClass && typeof componentClass.prefetchData === 'function') {
      componentClass.prefetchData({ store, params, location })
    }
  })
}
于 2016-07-22T08:46:01.887 回答