React-router urls don't work when refreshing or writing manually

前端 未结 30 2737
时光取名叫无心
时光取名叫无心 2020-11-21 05:07

I\'m using React-router and it works fine while I\'m clicking on link buttons, but when I refresh my webpage it does not load what I want.

For instance, I am in

30条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 05:47

    you can try reading this all though it's not mine:

    https://www.andreasreiterer.at/fix-browserrouter-on-apache/

    Fixing the app’s routing Now here’s how to finally fix the routing. To tell Apache to redirect requests to index.html where our app lives, we have to modify the .htaccess file. If there is no such file in your app’s folder yet, just create it.

    Then be sure that you put in those 4 lines that will magically make your routing work.

    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]
    

    After we put that .htaccess file into the same directory as the index.html, Apache will redirect each new request directly to your app.

    Bonus: Deploying the React app to a sub directory

    If you’re deploying your app into a sub directory, so it’s accessible e.g. via https://myapp.com/the-app, you’ll soon notice that there is another issue. Each click to a new route will transform the URL to something like https://myapp.com/route-abc – which will break again after a reload. But there is a simple fix for that:

    BrowserRouter has a prop called basename where you can specify your sub-directory path:

    From now on, each Route like /contacts will result in an URL like http://myapp.com/the-app/contacts.

提交回复
热议问题