我们有一个大型而复杂的传统 React 应用程序,我们在过去几年一直在构建它。它加载一个 index.html 注入(inject) javascript 并像往常一样从 API 获取数据。不幸的是,冷加载时间非常糟糕(平均 5 - 7 秒)。一旦一切都加载完毕,它会像往常一样快速,但冷加载时间正在特定的“关键”页面中杀死我们。这些是我们的公共(public)用户页面,格式为:https://mywebsite/userId
我们正在寻找一种方法来显着加快这些路由的加载时间,方法不仅限于代码拆分或资源优化。我们已经这样做了,并且正在通过 CDN 为我们的应用程序提供服务。
我们已经研究过创建这些用户页面的静态“快照”,我们需要使用诸如 react-static 之类的东西来非常快速地加载,并将它们作为静态版本提供并稍后对其进行补充。使用 next.js 或 gatsby 之类的东西重写我们的项目不是一种选择,因为它需要太多的工作。 SSR 也不是一种选择,因为我们的整个后端都是用 Django 而不是 Node.js 编码的
我们走在正确的轨道上吗?使用 react-static(或类似工具)来做到这一点是否可能/值得?有很多关于如何从头开始创建 react-static 项目的文档,但没有关于如何转换现有项目的文档,即使它只是我们需要的路由的一小部分。
此外,一旦我们用户页面上的数据发生变化,我们如何触发适当快照的“重建”?用户不会经常更新他们的数据,大约每月 4 次中的 3 次,但我们有 3K 用户,因此平均每小时更新 15 次。我们可以只触发实际更改的路由的重建吗?
最佳答案
就像你说的,你可以使用 react-static。
他们有一个功能可以完全满足您的需求(用户的特定页面)。
在他们的示例中,他们使用一组帖子为每个帖子生成一个特定的静态文件。
由于它只是 html 静态文件,因此加载所需的时间要少得多。
想象一下有这样一个场景:
[
{
id: 'foo',
...
},
{
id: 'bar',
...
},
...
]
按照下面的示例,这将生成如下内容(在运行时):- src
- pages
- blog
- posts
- foo // Specific post page
- bar // Specific post page
看一下例子://static.config.js
export default {
// resolves an array of route objects
getRoutes: async () => {
// this is where you can make requests for data that will be needed for all
// routes or multiple routes - values returned can then be reused in route objects below
// ATTENTION: In here, instead of posts you'd fetch your users json data
const { data: posts } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
return [
// route object
{
// React Static looks for files in src/pages (see plugins below) and matches them to path
path: "/blog",
// function that returns data for this specific route
getData: () => ({
posts
}),
// an array of children routes
// in this case we are mapping through the blog posts from the post variable above
// and setting a custom route for each one based off their post id
children: posts.map(post => ({
path: `/post/${post.id}`,
// location of template for child route
template: "src/containers/Post",
// passing the individual post data needed
getData: () => ({
post
})
}))
},
];
},
// basic template default plugins
plugins: [
[
require.resolve("react-static-plugin-source-filesystem"),
{
location: path.resolve("./src/pages")
}
],
require.resolve("react-static-plugin-reach-router"),
require.resolve("react-static-plugin-sitemap")
]
};
关于reactjs - 通过使用 "Snapshots"的关键路由(静态渲染)来加速大型 React 项目的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65315536/