【发布时间】:2019-03-21 20:58:46
【问题描述】:
当另一个组件更改查询/搜索字符串时,我需要一个组件来重新呈现。
要更改我正在使用 history.push() 的网址:
private updateURL(date: Date) {
const url = `/?date=${formatDate(date)}`; // /?date=2019-01-01
history.replaceState(
{},
`Dashboard for ${formatDate(date)}`,
url
);
}
在我的导航栏中,我想更新我的链接,以便它们可以在 URL 之间共享查询字符串。如果我使用withRouter,这将有效:
class Sidebar extends React.Component {
public render(){
return <Link to={`/anotherPage?${this.props.location.search}`}>Visit</Link>;
}
}
export default withRouter(Sidebar);
如果我使用 Redirect 对象而不是 history.push(),侧边栏会按应有的方式更新,这很好。这是否意味着它将卸载整个视图,呈现重定向,然后重新安装整个视图?例如,如果这意味着卸载和重新安装复杂的 svg 地图,那将是不可取的。
constructor(props){
super(props);
this.state = {
redirect: null;
}
}
private updateURL(date: Date){
this.setState({
redirect: `/?date=${formatDate(date)}`
});
}
public render(){
if (this.state.redirect){
return <Redirect to={this.state.redirect} />;
} else {
// render dashboard, map, charts, etc.
}
}
如果我不能或不想使用<Redirect />,是否有替代方法可以在查询字符串因 history.push 而更改时导致侧边栏更新?
【问题讨论】:
-
这篇文章可能对你有所帮助stackoverflow.com/questions/48993247/…
标签: javascript reactjs react-router query-string