我知道这方面有很多问题,但我似乎无法让它发挥作用:我需要从通过路由呈现的子组件中访问“历史记录”。(它接收来自redux容器的道具)。
我需要将历史对象传递给每个路由中呈现的组件,这样我就可以在子组件中使用this.props.history.push('/route')
。这个应用程序以前不太动态,所以每个路由都是用component={someComponent}
硬编码的;但是我发现在动态地执行路由时,您需要使用render={() => <someComponent />}
。
在更改了从component={}
到render={() => ...}
的路由后,我丢失了子组件中的历史记录。
我的代码就像:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import { HashRouter as Router, Link, Route, Redirect } from 'react-router-dom';
import { Nav_Item } from '.'
import DynamicTab from '.';
export default class NavBar extends React.Component {
constructor(props) {
super(props);
this.state={}
}
render() {
let tabs = [];
let routes = [];
this.props.tabs.forEach( function(tab, index) {
tabs.push(<Nav_Item key={tab.name} path_name={'/' + tab.name} tab_text={tab.label} />);
routes.push(<Route key={tab.name} path={'/' + tab.name} render={() => <DynamicTab tabName={tab.name} tabSpecs={tab} />} />);
})
return (
<Router>
<div>
<div>
<ol>
{ tabs }
</ol>
</div>
<Redirect to={'/' + this.props.tabs[0].name} />
{ routes }
</div>
</Router>
)
}
}
发布于 2017-09-12 11:58:00
当你使用render
时,你实际上得到了道具。在文档中有这样一个例子:
<Route {...rest} render={props => (
<FadeIn>
<Component {...props}/>
</FadeIn>
)}/>
所以你应该可以从这些道具中获取历史记录。
另一种解决方案是有条件地呈现一个<Redirect/>
组件。所以,也许你有一些内部状态,你可以这样使用:
// in your components render function..
if(this.state.shouldRedirect) {
return (<Redirect to={yourURL} />);
}
发布于 2019-09-10 00:42:53
this.props.router
和你可以访问任何你想要的东西。
在你的情况下,你可以做:
this.props.router.push("/newurl");
如果此组件由路由器呈现,则不需要将历史记录作为单独的属性传递。
https://stackoverflow.com/questions/46184284
复制