gpt4 book ai didi

reactjs - React服务端渲染中如何基于动态路由路径获取数据

转载 作者:行者123 更新时间:2023-12-03 13:39:03 30 4
gpt4 key购买 nike

假设我有一个如下所示的组件。

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
}

我正在使用带有react-router-config设置的react-router v4。我已经没有主意了。如何在服务器内获取 userSlugName。

现在如何在服务器中预取这些详细信息以使 SSR 正常工作。

最佳答案

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

基本思想如下:

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

您可以尝试 Redux 网站 ( https://redux.js.org/recipes/server-rendering#async-state-fetching ) 或本教程 ( https://www.sitepoint.com/asynchronous-apis-server-rendered-react/ ) 中提到的方法。

我更喜欢后者,它更通用,并且您不需要为每个组件使用不同的获取代码。不过,您可能想要调整代码以使其更简单。有关 React Router 上下文 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));
}

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

关于reactjs - React服务端渲染中如何基于动态路由路径获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48281241/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com