[英]history.push() and <Redirect /> not working
我已經嘗試了大約 5-7 種不同的關於重定向和歷史的解決方案,這些解決方案不適用於 react-router。 這是 create-react-app 代碼:
索引.js
import { Router} from 'react-router-dom';
import history from './History';
ReactDOM.render(<Router history={history}><App /></Router>, document.getElementById('root'));
歷史.jsx
import {createBrowserHistory} from 'history';
export default createBrowserHistory();
啟動畫面.jsx
return (
<ViewContext.Provider value={this.state.contextChangeUtils}>
<WrappedComponent/>
</ViewContext.Provider>
);
應用程序.jsx
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
}
//...
const routes = [{
path: '/',
component: MainPage,
}, {
path: '/status-history',
component: HistoryPage,
}, {
path: '/status-details',
component: DetailsPage
}]
if (this.context.viewInfo.path!==this.state.lastPath) {
this.setState({lastPath: this.context.viewInfo.path});
let { history } = this.props;
history.push(this.context.viewInfo.path);
}
return (
<Container className="App pl-0 pr-0">
<StatusHeader />
<Row>
<Col md="1" />
<Col md="2" className="TagListOuter">
<TagList tags={tags} />
</Col>
<Switch>
{routes.map(r => (
<Route path={r.path} key={r.path} component={r.component} />
))}
</Switch>
</Row>
</Container>
);
App.contextType = ViewContext;
export default SplashScreen(withRouter(App));
關於可能出什么問題的任何想法? 提前致謝
this.props.history.push({
pathname: "Your path",
state: {
lastPath: this.context.viewInfo.path
}
});
您可以使用this.props.location.state
或this.props.location.state.lastPath
獲取數據
如果您創建了一個自定義歷史實例來管理您的React路由器歷史記錄和調用函數,那么請按如下方式使用它,而不是導入withRouter並將其注入到組件中。
import history from "../History.js"
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
}
//...
const routes = [{
path: '/',
component: MainPage,
}, {
path: '/status-history',
component: HistoryPage,
}, {
path: '/status-details',
component: DetailsPage
}]
if (this.context.viewInfo.path!==this.state.lastPath) {
this.setState({lastPath: this.context.viewInfo.path});
history.push(this.context.viewInfo.path);
}
return (
<Container className="App pl-0 pr-0">
<StatusHeader />
<Row>
<Col md="1" />
<Col md="2" className="TagListOuter">
<TagList tags={tags} />
</Col>
<Switch>
{routes.map(r => (
<Route path={r.path} key={r.path} component={r.component} />
))}
</Switch>
</Row>
</Container>
);
App.contextType = ViewContext;
export default SplashScreen(App);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.