假设我的应用程序的基本URL是example.com/app
是否可以在react-router中设置基本路由,而不是将所有路由都写为
/app/a
/app/b
/app/c
Run Code Online (Sandbox Code Playgroud)
我可以将它们指定为
a
b
c
Run Code Online (Sandbox Code Playgroud)
我尝试了以下我在文档中找到的示例,但它不起作用(页面不会显示任何内容).也许是因为我正在使用react-router@3.0.0-alpha.1,或者我做错了什么.
import { useRouterHistory } from 'react-router'
import { createHistory } from 'history'
const history = useRouterHistory(createHistory)({
basename: '/app'
})
const Root = ({store}) => (
<Provider store={store}>
<Router history={history}>
<Route path='/' component={App}>
...
</Route>
</Router>
</Provider>
)
Run Code Online (Sandbox Code Playgroud) 我正在使用react-router-dom和create-react-app。
运行脚本yarn start,它以http://localhost:3000/(myprojectname),而不是开头http://localhost:3000/
当使用react-router-dom进行路由时,我必须myprojectname从url中删除,然后添加页面路由。
项目的初始设置好像有问题,
我该如何开始http://localhost:3000/?
添加package.json、路由器代码。
包.json:
{
"name": "cau-burger-online-order-system",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.4",
"@testing-library/react": "^11.1.0",
"@testing-library/user-event": "^12.1.10",
"@types/jest": "^26.0.15",
"@types/node": "^12.0.0",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@types/react-router-dom": "^5.3.2",
"@types/styled-components": "^5.1.16",
"axios": "^0.24.0",
"bootstrap": "^5.1.3",
"brace-expansion": "^2.0.1",
"gh-pages": "^3.2.3",
"prettier": "^2.5.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "5.3.0",
"react-scripts": "4.0.3",
"styled-components": "^5.3.3",
"typescript": "^4.1.2",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": …Run Code Online (Sandbox Code Playgroud) 需要<base href=""/>根据构建环境配置设置标记的href值.
例如:
分期应该有 <base href="/staging" />
产品应该有 <base href="/" />
目前的设置:
构建命令:
"build": "sh -ac '. .env.${REACT_APP_ENV}; react-scripts build'",
"build:staging": "REACT_APP_ENV=staging npm run build",
"build:prod": "REACT_APP_ENV=production npm run build",
Run Code Online (Sandbox Code Playgroud)
.env.staging.js:
REACT_APP_BASE_HREF=/staging
Run Code Online (Sandbox Code Playgroud)
index.html的:
....
<base href="" + process.env.REACT_APP_API_URL />
....
Run Code Online (Sandbox Code Playgroud)
这在index.html中似乎不起作用.虽然类似的设置适用于JS文件
(可能是因为JS文件被解析并捆绑到一个文件中,并且捆绑器在那个时间点读取值)
事情尝试:
index.html的:
<base href=process.env.REACT_APP_API_URL />
<base href="process.env.REACT_APP_API_URL" />
<base href="%process.env.REACT_APP_API_URL%" /> (类似于PUBLIC_URL变量)
设置basename属性以及浏览器路由器也无法解决问题