react-router-dom 仅适用于重新加载,是否有任何解决方案或其他方法可以重定向到其他页面?

react-router-dom only works on reload, is there any solution or another way to redirect to other pages?

我正在尝试使用“react-router-dom”和“history”模块重定向到 reactjs 中的另一个页面。但它改变了 url 并加载了一个空白视图,需要重新加载才能加载组件。

这是我的代码:

index.js :

import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter} from "react-router-dom";
import Routes from "./routes";

ReactDOM.render(
  <React.StrictMode>
      <BrowserRouter>
        <Routes/>
      </BrowserRouter>

  </React.StrictMode>,
  document.getElementById('root')
);

reportWebVitals();

routes.js

import { Router, Switch, Route } from 'react-router-dom'
import FirstPage from "./first";
import SecondPage from "./seconsPage";
import history from "./history";

export default function Routes() {
    return(
        <Router history={history}>
            <Switch>
                <Route path="/" exact component={FirstPage} />
                <Route path="/second" component={SecondPage} />

            </Switch>
        </Router>
    )
}

history.js

import {createBrowserHistory as history} from "history";

export default history();

first.js

export default function FirstPage() {
    const btnClicked = () => {
        history.push('/second');
    };
    return(
        <div>
            <h3>First Page</h3>
            <button onClick={btnClicked}>click</button>
        </div>

    )
}

seconsPage.js

export default function SecondPage() {
    return(
        <h3>Second Page</h3>
    )
}

我使用“history”v5.0.0 和“react-router-dom”v5.2.0

我也尝试了超过 whosebug.com 的所有解决方案,但其中 none 对我有用。 是否有任何解决方案或其他模块或方法或教程可以重定向到 reactjs 中的其他页面?

为了使其正常工作,请使用 history v4,例如4.10.1.

请发现它在这里工作:https://codesandbox.io/s/cocky-tdd-oecnk

package.json:

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

以及原因:https://github.com/ReactTraining/history

Documentation for version 5 can be found in the docs directory. This is the current stable release. Version 5 is used in React Router version 6.

Documentation for version 4 can be found on the v4 branch. Version 4 is used in React Router versions 4 and 5.