假设我的应用的基本网址是 example.com/app
是否可以在react-router中设置基本路由,而不是将所有路由写为
/app/a /app/b /app/c
我可以将它们指定为
a b c
我尝试了在文档中找到的以下示例,但它不起作用(页面不会显示任何内容)。也许是因为我使用的是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}) => ( ... )
如果您想使用
,它可以让您访问历史对象,允许您通过history.push('/my-path')更改页面code>直接来自js的方法。您将面临这样的问题:BrowserRouter 没有可用的history属性,并且 Router 没有可用的basename。解决办法如下:
const App: React.FC = () => { // do not put a slash at the end of the basename value. const history = createBrowserHistory({ basename: '/your-base-name' }); return ... ; }https://reacttraining.com/react-router/web/ api/BrowserRouter/basename-string
使用最新的react router (v4),你可以轻松做到这一点