TL;DR - 我希望我的 React 应用程序以相对路径 domain.com/tweets 开头
大家好,我正在创建一个从 Twitter API 获取推文的 React 应用程序。
因为整个应用程序只是一个内置在 react 中的 SPA,我认为创建一个带有导航到推文页面的链接的空主页是错误的,而不是立即将推文显示为“主页”。同样,目前,显示推文是该应用程序唯一要做的事情。
因此,我一直在寻找一种方法来启动我的应用程序,并在域名之后使用路径“/tweets/”。
我知道我可以使用两种选择,但我不确定使用哪一种:
- package.json "主页": "/tweets" 属性
- React router 导航到="/tweets" 组件
与 package.json 主页选项相比,我更喜欢重定向的行为,因为我真的没有主页,它会阻止用户尝试访问 domain.com,而是将他们重定向到 domain.com/tweets。
#EDIT 1
在您的回答中,请注意我使用的是 React Router V6,因为您可能知道之前的一些功能可能不再相关。
我应该选择什么选项?我错过了什么吗?上传到生产时这会给我带来问题吗?
这是我目前的解决方案:
<BrowserRouter>
<Routes>
<Route path="/tweets" element={<App />}>
<Route path=":pageNumber" />
</Route>
<Route
path="*"
element={<Navigate to="/tweets"/>}
/>
</Routes>
</BrowserRouter>
编辑#2 - 这是更新的代码
<BrowserRouter>
<Routes>
<Route path="/tweets/:currentPageNumber" element={<App />}/>
<Route path="/*" element={<Navigate to="/tweets/1" />} />
</Routes>
</BrowserRouter>
回答1
您的 React 应用程序是否会拥有多个页面?如果答案是否定的,那么我根本看不到使用任何路由有任何意义。
我建议的两个选项是:
在
package.json
文件中使用"homepage": "."
条目,因此您使用的任何路由都可以相对于应用程序的部署位置工作。将您的应用程序部署到服务器上的"/tweets"
子目录。如果您稍后决定确实需要向应用程序添加其他页面和路由,请将basename
prop 指定给您选择使用的路由器组件。<BrowserRouter basename="/tweets"> <Routes> <Route path="/" element={<App />}> <Route path=":pageNumber" /> </Route> </Routes> </BrowserRouter>
在
package.json
文件中使用"homepage": "."
条目,以便使用的任何路由都相对于应用程序部署位置起作用。将应用部署到根目录并处理重定向到"/tweets"
路由。<BrowserRouter> <Routes> <Route path="/tweets" element={<App />}> <Route path=":pageNumber" /> </Route> <Route path="*" element={<Navigate to="/tweets" replace />} /> </Routes> </BrowserRouter>
有关详细信息,请参阅https://create-react-app.dev/docs/deployment/#building-for-relative-paths。