如何基于动态路由路径获取反应服务器端呈现中的数据

Akh*_*l P 5 reactjs server-side-rendering react-ssr

假设我有一个如下组件.

User extends React.Component {
  componentDidMount() {
    this.props.fetchUserDetails(this.props.params.userSlugName);
    // this slug name is coming from route params (ex: path is /users/:userSlugName)
  }
  // Other lifecycle methods
}

User.loadData = () => {
  // some data fetching logic for backend
}
Run Code Online (Sandbox Code Playgroud)

我正在使用react-router v4和react-router-config设置.我的想法已经不多了.如何在服务器中获取userSlugName.

现在,我如何在Server for SSR中预取这些详细信息才能正常工作.

Kir*_*ira 0

在服务器端渲染中合并异步逻辑有点棘手。当你调用 renderToString() 时,你将获得初始 render() 的 html。您需要的是后续 render() 的 html,该渲染在数据传入时发生。

基本思想如下:

  • 执行 API 调用
  • 等他们完成
  • 返回最终渲染的 html()

您可以尝试 Redux 网站 ( https://redux.js.org/recipes/server-rendering#async-state-fetching ) 或本教程 ( https://www.sitepoint.com/asynchronous-apis ) 上提到的方法-服务器渲染反应/)。

我更喜欢后者,它更通用,并且您不需要为每个组件使用不同的获取代码。不过,您可能想要调整代码以使其更简单。有关 React 路由器上下文 API 的更多详细信息,请参见:https://medium.freecodecamp.org/how-to-protect-your-routes-with-react-context-717670c4713a

function handleRender(req, res) {
    const fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
    console.log('fullUrl: ', fullUrl);
    console.log('req.url: ', req.url);

    // Create a new Redux store instance
    const store = createStore(reducerFn);
    const context = {};    // Store stuff here

    const urlToRender = req.url;
    // Render the component to a string
    const html1 = renderToString(
        <Provider store={store}>
            <StaticRouter location={urlToRender} context={context}>
                {routes}
            </StaticRouter>
        </Provider>
    );

    // Get promises from context, wait for all of them to finish
    // Render again
    const html = renderToString(
        <Provider store={store}>
            <StaticRouter location={urlToRender} context={context}>
                {routes}
            </StaticRouter>
        </Provider>
    );
    const helmet = Helmet.renderStatic();

    // Grab the initial state from our Redux store
    const preloadedState = store.getState();

    // Send the rendered page back to the client
    res.send(renderFullPage(helmet, html, preloadedState));
}
Run Code Online (Sandbox Code Playgroud)

当我有机会时,我会分享https://www.heloprotocol.in/的代码。