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

IT技术 reactjs react-router
2021-05-06 15:01:47

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

索引.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'),
);

根.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我没有问题但如果我history.push()在 tsx 文件之外使用时 BrowserRouter 不起作用这就是为什么我需要使用它Router有一个类似的问题React router 重定向页面但组件没有被渲染,但我认为我的路由器包装了主要的应用程序组件。我在代码中错误配置了什么?

1个回答

Router在为它提供一个历史对象后,你的代码看起来是正确的

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

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

而且,还要确保您使用的4.0版本history,不是第5版(开放问题)