react app showing empty page when redirecting on production build

半世苍凉 提交于 2021-02-05 06:42:46

问题


I have a reactJs app which is running on a server that has nginx on it. The problem is that when I try to redirect from HomePage("/") to /UserPanel or /AdminPanel the url changes but it shows an empty page, but then when i reload the page, it works just fine. This problem doesn't occur in my localhost, but it happens to the production build.

this is my nginx config:

        listen 80 default_server;
        listen [::]:80 default_server;

       
        root /var/app/html;

        index index.html index.htm;

        location / {
                try_files $uri $uri/ /index.html?$args;
        }

And this is my main app class:

import { Route, Router, Switch } from "react-router-dom";

class App extends Component {
  render() {
    return (
      <Provider store={store}>
        <Snackbar />
        <Router history={hist}>
          <MuiThemeProvider theme={theme}>
            <CssBaseline />
            <GlobalStyles />
            <Pace color={theme.palette.secondary.main} />
            <Suspense fallback={<Fragment />}>
              <Switch>
                <PrivateRoute
                  path="/AdminPanel"
                  component={AdminPanel}
                />
                <PrivateRoute
                  path="/UserPanel"
                  component={UserPanel}
                />
                <Route exact path="/" component={HomePage} />
              </Switch>
            </Suspense>
          </MuiThemeProvider>
        </Router>
      </Provider>
    );
  }
}

And I am redirecting from HomePage like this:

const redirect = () => {
    let url = isAdmin
      ? URLConstant.ADMIN_PANEL
      : isUser
      ? URLConstant.USER_PANEL
      : null;
    if (url) {
      return (
        <Redirect
          push
          to={{
            pathname: url,
            state: {}
          }}
        />
      );
    }
  };

And I'm using "react-router": "^5.2.0", "react-router-dom": "^5.2.0", "history": "latest".

What am I doing wrong? Should I add anything other than urls in .env? Thanks in advance.


回答1:


Downgrade your "history" version or simply remove it because the correct version will be automatically added by "react-router-dom".

There is already an open issue about the same: https://github.com/ReactTraining/history/issues/804

Which says React Router (mainly history.push and Redirect) is not working properly with latest (v5) version of history. But it is working perfectly with v4 of history.

For example, this should work:

    "history": "^4.10.1",
    "react-router-dom": "^5.2.0",



回答2:


Use a "homepage": ".", inside your package.json.



来源:https://stackoverflow.com/questions/65983627/react-app-showing-empty-page-when-redirecting-on-production-build

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