Basename not working properly

后端 未结 3 2061
闹比i
闹比i 2021-02-20 03:20

I\'m attempting to use a basename with react-router as documented on the react-router docs. This is due to base href being deprecated.

Here is what I have now:

相关标签:
3条回答
  • 2021-02-20 03:43

    Using BrowserRouter

    helpers/history.js

    import { createBrowserHistory } from "history";
    export default createBrowserHistory();
    

    index.js

    import {BrowserRouter as Router} from "react-router-dom";
    import history from "helpers/history";
    .....
    
    <Router history={history} basename={'/app'}>  
    ...
    </Router>
    

    Using Router

    helpers/history.js

    import { createBrowserHistory } from "history";
    export default createBrowserHistory({ basename: '/app' });
    

    index.js

    import {Router} from "react-router-dom";
    import history from "helpers/history";
    ....
    
    <Router history={history}>  
    ...
    </Router>
    
    0 讨论(0)
  • 2021-02-20 03:58

    Here is how I managed to get it to work

    Set Router basename to your subdirectory like this

    <Router basename="/subdirectory">

    If you used create-react-app and are building using npm run build you need to set homepage in package.json for the paths to be correct in the production build

    homepage: "{http://www.the-url.com/subdirectory}"

    For the nginx config, let's assume your index.html is under /path/to/subdirectory/index.html. Then the following should work

    location /subdirectory {
        root /path/to;
        try_files $uri $uri/ /subdirectory/index.html;
    }
    
    0 讨论(0)
  • 2021-02-20 03:58

    I solved it by using:

    import { Router, useRouterHistory } from 'react-router'
    import createBrowserHistory from 'history/lib/createBrowserHistory'
    
    const history = useRouterHistory(createBrowserHistory)({
        basename: '/',
    })
    
    <Router history={history}>
    

    I think the issue was different versions of the history package. react-router@2.2.4 uses history@2.1.2, while history is already at 4.5.1. So make sure you install the correct version of the history package.

    0 讨论(0)
提交回复
热议问题