问题
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