问题描述
我在 react-router 2.x 配置方面遇到了一些困难,特别是应用 basename.
I'm struggling a bit with react-router 2.x configuration, specifically app basename.
我有一个应用程序,它在整个生命周期中可能具有不同的基本根.例如:
I've an application which may have different base root throughout its lifecycle. For instance:
/
开发中/users
生产中/account
迁移后生产中
/
in development/users
in production/account
in production after migration
基本名称在几个地方发挥作用:
The basename comes into play in several places:
- Webpack 中的静态资源编译
- react-router 主要配置
- 在 redux 操作中指定重定向路由
- 向 API 调用提供诸如
redirectUrl
之类的东西
- static asset compilation in Webpack
- react-router main configuration
- specifying redirect routes in redux actions
- providing something like
redirectUrl
to API calls
我目前的解决方案是拥有一个 ENV 变量,并通过 Express 服务器注入 window.defs
使其对 Webpack 和应用程序本身都可用,但我最终还是得到了诸如 ${defs.APP_BASENAME}/signin
在整个应用程序中的位置太多.
My current solution is to have an ENV variable and make it available both to Webpack and to the app itself by injecting window.defs
via an Express server, but I still end up having things like ${defs.APP_BASENAME}/signin
in way too many places throughout the app.
我如何抽象应用程序库,或者至少将其隐藏在一个位置?我应该能够在路由器的配置中指定基本路由,然后以某种方式简单地使用相对路由,对吗?还是我遗漏了什么?
How can I abstract the app base, or at least tuck it away in a single location? I should be able to specify the base route in Router's config, and then simply use relative routes somehow, right? Or am I missing something?
推荐答案
你可以用 .您可以将其与 Webpack 配置中的 DefinePlugin
混合使用,以指定应使用哪个基本名称.
You can decorate your history
with a basename. You could mix this with a DefinePlugin
in your Webpack configuration to specify which basename should be used.
// webpack.config.js
new Webpack.DefinePlugin({
BASENAME: '/users'
})
// somewhere in your application
import { useRouterHistory } from 'react-router'
import { createHistory } from 'history'
const history = useRouterHistory(createHistory)({
basename: BASENAME
})
给定基本名称:/users
,React Router 将忽略路径名开头的 /users
所以:
Given the basename: /users
, React Router will ignore the /users
at the beginning of the pathname so:
URL
/users
内部匹配路径/
URL /users/profile
匹配路径 /profile
.
The URL /users/profile
matches the path /profile
.
同样,当您在应用程序中导航时,您不必将基本名称附加到路径中.
Similarly, you do not have to append the basename to the path when you are navigating within your application.
将在内部导航到
/friends
,但地址栏中的 URL 将是 /users/friends.
<Link to='/friends'>Friends</Link>
will navigate to/friends
internally, but the URL in the location bar will be/users/friends
.
这篇关于在反应路由器中配置应用程序的基本名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!