React router Redirection仅在重新加载时显示页面



我在react应用程序中使用react路由器,在启动该应用程序时遇到问题。首先,我得到了一个没有任何错误的空白页面,当我重新加载页面时,我得到的是内容。

index.tsx:

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import Root from './app/Root';
import * as serviceWorker from './serviceWorker';
import store from './app/store';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Root />
</Provider>
</React.StrictMode>,
document.getElementById('root'),
);

Root.tsx:

import React from 'react';
import {Route, Router, Switch} from 'react-router-dom';
import App from './App';
import SignIn from 'features/authentication/signIn/SignInContainer';
import SignUp from 'features/authentication/signUp/SignUpContainer';
import history from 'browserHistory/index';
const Root = (): JSX.Element => (
<Router history={history}>
<Switch>
<Route exact path="/" component={App} />
<Route exact path="/signin" component={SignIn} />
<Route path="/signup" component={SignUp} />
</Switch>
</Router>
);
export default Root;

当我尝试BrowserRouter而不是Router时,我没有问题,但如果我在tsx文件之外使用history.push(),BrowserRouter就不起作用。这就是为什么我需要使用Router。还有一个类似的问题React路由器重定向页面,但组件没有被渲染,但我认为我的路由器包裹了主要的应用程序组件。我在代码中误解了什么?

您的代码似乎是正确的,因为Router在为其提供历史对象后才能工作。

因此,请确保您已正确创建history:

import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;

此外,还要确保您使用的是history的第4版,而不是第5版(公开发行(。

最新更新