我可以在react-router中设置基本路由

gal*_*lki 50 react-router

假设我的应用程序的基本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)

gal*_*lki 70

使用最新的反应路由器(v4),您可以轻松完成此操作

<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="/calendar/today">
Run Code Online (Sandbox Code Playgroud)

  • 在这里需要指出的是,文档关于 &lt;BrowserRouter&gt; 标记的正确用法似乎是错误的。文档中看到的自关闭标签将不起作用。您需要将 &lt;BrowserRouter&gt; 标记包裹在所有 &lt;Link&gt; 和其他路由标记周围。该示例应为: &lt;BrowserRouter basename="/calendar"&gt; &lt;Link to="/today"/&gt;&lt;Link to="/tomorrow"/&gt; ... &lt;/BrowserRouter&gt; (5认同)
  • 有没有办法用动态路径字段来做到这一点?像`/calendar/:year/:month/:day/event` 可能是,例如,`/calendar/11/4/21/event` (3认同)
  • 为什么不将`:year /:month /:day/event`部分放在链接中=? (3认同)

Amb*_*ier 16

如果你想使用<Router />,它可以让你访问历史对象,允许你history.push('/my-path')直接从 js 中通过方法更改页面。你会面临 BrowserRouter 没有historyprop 可用,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 <Router history={history}>
           ...
         </Router>;
}
Run Code Online (Sandbox Code Playgroud)

所有位置的基本 URL。如果您的应用程序是从服务器上的子目录提供的,您需要将其设置为子目录。格式正确的基本名称应该有一个前导斜杠,但没有尾随斜杠

https://reacttraining.com/react-router/web/api/BrowserRouter/basename-string