我已经根据这篇文章How to get history on react-router v4?实现了createBrowserHisotry,但是只有在我将配置属性设置为forceRefresh:true时,它才会重定向。如果我未设置任何配置属性,则该网址将更改为推送的网址,但该页面将不会重定向。为什么?
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();
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
});
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;
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);
答案 0 :(得分:7)
使用此:
this.props.history.push('/index');
this.props.history.go();
答案 1 :(得分:0)
您的代码中的问题是您正在使用多个路由器组件。在index.js组件中不需要路由器。而是仅在App中呈现它并提供自定义历史记录
index.js
ReactDOM.render(<App />,
document.getElementById('root'));
registerServiceWorker();
然后像这样传递道具的自定义历史记录
<Router history={history}>
{/* rest of the code */}
</Router>
其中history
是从common/history.js
导入的