React-router 重定向仅在重新加载时显示页面

时间:2021-04-02 23:45:25

标签: reactjs react-router

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

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 redirects the page but component doesn't get rendered 但我认为我的路由器包装了主要的应用程序组件。我在代码中错误配置了什么?

1 个答案:

答案 0 :(得分:2)

您的代码似乎是正确的,因为 Router 在提供 history object 后可以工作。

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

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

而且,还要确保您使用的是 version 4history,而不是 version 5 (open issue)