假设我的应用程序的基本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)
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
| 归档时间: |
|
| 查看次数: |
37033 次 |
| 最近记录: |