[英]How to update component that is being rendered on route of 'react-router-dom'?
[英]React Router: access history in rendered Route component
我知道有很多问题,但我似乎无法让它工作:我需要从通过路由呈现的子组件访问“历史”。 (它从redux容器接收道具)。
我需要将历史对象传递给每个Route中呈现的组件,以便我可以在子组件中使用this.props.history.push('/route')
。 此应用程序之前的动态性较差,因此每个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>
)
}
}
当你使用render
你实际上得到道具。 在文档中,他们有一个这样的例子:
<Route {...rest} render={props => (
<FadeIn>
<Component {...props}/>
</FadeIn>
)}/>
因此,您应该能够从这些道具中访问历史记录。
另一种解决方案是有条件地渲染<Redirect/>
组件。 所以也许你有一些你使用的内部状态:
// in your components render function..
if(this.state.shouldRedirect) {
return (<Redirect to={yourURL} />);
}
this.props.router
,你可以访问你想要的任何东西。
在你的情况下,你可以这样做:
this.props.router.push("/newurl");
如果路由器呈现此组件,则无需将历史记录作为单独的属性传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.