当查询字符串改变时更新反应组件
Updating react components when the query string changes
我需要一个组件在另一个组件更改 query/search 字符串时重新呈现。
要更改 url 我正在使用 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 发生更改时更新边栏?
例如,您可以通过将 console.log
放在 componentDidMount
中来轻松检查它,但考虑到 React 的工作原理,我相信它会像您怀疑的那样 unmount/mount。因此,更好的解决方案是使用 react-router 还提供的 history.replace()
API:
private updateURL(date: Date){
this.props.history.replace(`/?date=${formatDate(date)}`);
}
我需要一个组件在另一个组件更改 query/search 字符串时重新呈现。
要更改 url 我正在使用 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 发生更改时更新边栏?
例如,您可以通过将 console.log
放在 componentDidMount
中来轻松检查它,但考虑到 React 的工作原理,我相信它会像您怀疑的那样 unmount/mount。因此,更好的解决方案是使用 react-router 还提供的 history.replace()
API:
private updateURL(date: Date){
this.props.history.replace(`/?date=${formatDate(date)}`);
}