我已经尝试了大约5-7种关于重定向和历史记录的不适用于React-router的解决方案。 这是create-react-app代码:
index.js
import { Router} from 'react-router-dom';
import history from './History';
ReactDOM.render(<Router history={history}><App /></Router>, document.getElementById('root'));
History.jsx
import {createBrowserHistory} from 'history';
export default createBrowserHistory();
SplashScreen.jsx
return (
<ViewContext.Provider value={this.state.contextChangeUtils}>
<WrappedComponent/>
</ViewContext.Provider>
);
App.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));
关于什么可能是错误的任何想法?预先感谢
答案 0 :(得分:0)
this.props.history.push({
pathname: "Your path",
state: {
lastPath: this.context.viewInfo.path
}
});
您可以使用this.props.location.state
或this.props.location.state.lastPath
答案 1 :(得分:0)
如果您创建了一个自定义历史记录实例来管理您的React Router历史记录和调用函数,那么请按以下方式使用它,而不是导入 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);