React history.push 需要强制刷新

React history.push requiring a forceRefresh

我已经根据此 post 实现了 createBrowserHisotry,但是它仅在我将配置 属性 设置为 forceRefresh: true 时才重定向。如果我不设置任何配置属性,url 将更改为推送的 url,但页面不会重定向。为什么?

INDEX.JS

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./components/App";
import { Router } from 'react-router-dom'
import registerServiceWorker from "./registerServiceWorker";
import history from "./components/common/History";

ReactDOM.render(<Router history={history}><App /></Router>, 
document.getElementById('root'));
registerServiceWorker();

HISTORY.JS

import createBrowserHistory from 'history/createBrowserHistory';

// export default createBrowserHistory(); --> This redirects the ### ### URL 
// but does not physically redirect

export default createBrowserHistory({
//pass a configuration object here if needed
forceRefresh: true
});

APP.JS

class App extends Component {

  render() {
    return (
      <Provider store={store}>
        <OidcProvider store={store} userManager={userManager}>
         <Router>
           <div className="container-fluid">
            <div>
             <Header />
            </div>
           <div>
            <Route exact path="/" render={props => <LoginForm auth={this.auth} {...props} />} />
            <Route exact path="/callback" render={props => <Callback auth={this.auth} {...props} />} />
            <Route exact path="/home" render={props => <HomePage {...props} />} />
            <Route exact path="/table" render={props => <TableContainer {...props} />} />
            <Route exact path="/form/:id" render={props => <FormContainer id={this.props.params.id} {...props} />} />
            <Route exact path="/form" render={props => <FormContainer {...props} />} />
          </div>
          <Footer />
        </div>
      </Router>
    </OidcProvider>
  </Provider>
);
}
}

 export default App;

另一个文件调用 history.push

import history from "../components/common/History";

class CallbackPage extends React.Component {
render() {
    // just redirect to '/' in both cases
    return (
        <CallbackComponent
            userManager={userManager}
            successCallback={() => history.push("/home")}
            errorCallback={error => {
                history.push("/");
                console.error(error);
            }}
        >
            <div>Redirecting...</div>
        </CallbackComponent>
    );
   }
}


export default connect()(CallbackPage);

您的代码中的问题是您使用了多个路由器组件。 index.js 组件中不需要 Router。而只是在 App 中呈现它并提供自定义历史记录

index.js

ReactDOM.render(<App />, 
document.getElementById('root'));
registerServiceWorker();

然后将自定义历史记录作为 prop like

  <Router history={history}>
      {/* rest of the code */}
  </Router>

其中 history 是从 common/history.js

导入的

使用这个:

this.props.history.push('/index');    
this.props.history.go();