我为标头和内部创建了一个通用组件,有条件地渲染视图,但是每当路线更改时,我都必须手动刷新页面以查看更新的结果。
constructor(props) {
super(props);
this.state = {
headerType: {
home: ['/'],
stepper: ['/decisionAid'],
},
};
}
render() {
const { headerType } = this.state;
let type = Object.keys(headerType).find(data =>
headerType[data].includes(window.location.pathname),
);
return (
<Router history={history}>
<>
<Header type={type} />
<Switch>
<>
<Route path="/" exact component={HomePage} />
<Route path="/decisionAid" component={Stepper} />
<Route path="/notFound" component={NotFound} />
</>
</Switch>
</>
</Router>
);
}
当我更改页面时,由于URL的更改,标题应该自动更新,但我必须手动刷新它。
答案 0 :(得分:0)
为了使标题能够访问您的URL,并重新渲染Header
而又不重新渲染整个App
对象,您可以将Header
包裹在高阶成分withRouter
:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md
这样做可以让您在道具中访问match
,location
和history
。
import { withRouter } from "react-router-dom";
function Header(props) {
const path = props.location.pathname.slice(1);
return <h1>Hello {path}!</h1>;
}
const WrappedHeader = withRouter(Header);