reactjs - 动态路由在我的反应应用程序的构建版本中不起作用
问题描述
我在我的 create-react-app 中使用 react 路由器进行路由。所有路由都使用“npm start”(“react-scripts start”)按预期工作。
但是,现在我想部署我的应用程序,因此运行“npm run-scripts build”(“react-scripts build”)。之后我运行“serve -s build”来启动网络服务器。在我的 Web 应用程序的这个版本中,静态路由正常工作,但动态路由不工作。
静态路由配置的示例如下所示。此路由适用于 react 应用程序的开发模式和构建模式。示例 URL:“ http://localhost:5000/dashboard/viewData ”。
{
path: "/dashboard/viewData/",
component: withAuth(CrosstabTest),
exact: false
}
以下路线是动态的并且不起作用。但是,我的猜测是这不是由于“:processFlowItemId”,而是由于附加的URL参数。示例 URL:“ http://localhost:5000/dashboard/definition/1?id=0744a761-111c-446c-9bb5-2763c5c8bb04 ”。
{
path: "/dashboard/definition/:processFlowItemId",
component: withAuth(DefinitionContainer),
exact: false
}
当我在没有“?id=0744a761-111c-446c-9bb5-2763c5c8bb04”的情况下运行示例 URL 时,应用程序会加载组件,但由于缺少 id 参数,我收到错误消息。但至少这表明该路线总体上正常工作但参数存在问题。打开包含 id 字段的完整示例 URL 时,组件似乎根本没有加载(这意味着 react-router 不会将 URL 识别为路由中定义的模式的实例。
如前所述,仅在使用应用程序的构建版本时才会出现此问题。
编辑:
下面我更详细地描述代码:
我的路线有一个配置:
export const mainRoutes: any = [
{
path: "/dashboard/",
component: Dashboard,
exact: false
},
]
export const dashboardRoutes: any = [
{
path: "/dashboard/viewData/",
component: withAuth(CrosstabTest),
exact: false
},
{
path: "/dashboard/definition/:processFlowItemId",
component: withAuth(DefinitionContainer),
exact: false
},
]
主要路线(“mainRoute”)在这里呈现:
import { mainRoutes } from './routes/routes'
import { Switch, BrowserRouter, Route } from 'react-router-dom'
class App extends React.Component<any> {
public render() {
return (
<BrowserRouter>
{mainRoutes.map((route: any, i: number) => (
<Switch key={i}>
<Route key={i} path={route.path} component={route.component} exact={route.exact} />
</Switch>
))
}
</BrowserRouter>
)
}
}
export default App
在仪表板组件(“仪表板”)中,我渲染了一个子路由:
import { Switch, Route } from 'react-router-dom'
import { dashboardRoutes } from '../../routes/routes'
...
dashboardRoutes.map((route: any, i: number) => (
<Switch key={i}>
< Route exact={true} key={i} path={route.path} render={(props) => {
return <route.component key={i} {...props} />
}} />
</Switch>
))
...
解决方案
我有同样的问题,并通过将 BrowserRouter 换成 HashRouter 来解决它
推荐阅读
- javascript - 使用键数组将多个 s3 对象推入 1 个数组
- php - Wordpress functions.php - 如果条件杀死其他帖子内容
- php - 在用户登录 PHP MySQL 后显示用户名
- java - 具有 Java 应用程序高 CPU 使用率的树莓派
- rx-java2 - 优先合并
- python - 来自 Statsmodels 库的 Pythonseason_decompose 函数给出 ValueError
- python - 使用 django 登录的 Bcrypt
- c++ - 创建抽象基类型引用的初始化列表
- hibernate - 两个日期之间的查询+另一列在 Hibernate 5 中不起作用
- java - 在 getTables() 方法中在哪里指定数据库名称。