How to configure a basename in React Router 3.x

半城伤御伤魂 提交于 2019-12-11 01:14:20

问题


I have an app running at a nested url as opposed to the root. Lets say example.com/app.

I read here that in react router 2.x you could configure basenames.

How can this be done in react router 3.x?

FYI I am also using the react-router-redux package.


回答1:


This functionality does not exist in React Router anymore. I went through a similar problem and found this fix.

Step 1: Install History (3.0.0)

npm install --save history@3.0.0

Step 2: Import { useBasename } from history in your router file (the file with <Router>):

import { useBasename } from 'history'

Step 3: Modify your <Router> like the below example:

<Router history={ useBasename(() => browserHistory)({ basename: '/app' }) }>




回答2:


I think the section on configuring histories in the React Router docs is what you're looking for:

https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md#customize-your-history-further

Here's a full example integrating with react-router-redux (with some unnecessary info excluded):

import React from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { useRouterHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';

import Root from './containers/Root';
import configureStore from './store/configureStore';

const historyConfig = { basename: '/some-basename' };
const browserHistory = useRouterHistory(createBrowserHistory)(historyConfig);

const store = configureStore({ initialState, browserHistory });
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: (state) => state.router,
});

ReactDOM.render(
  <Root history={history} store={store} />,
  document.getElementById('root')
);


来源:https://stackoverflow.com/questions/42181889/how-to-configure-a-basename-in-react-router-3-x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!