【问题标题】:Updating react components when the query string changes查询字符串更改时更新反应组件
【发布时间】: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.
  }
}

如果我不能或不想使用&lt;Redirect /&gt;,是否有替代方法可以在查询字符串因 history.push 而更改时导致侧边栏更新?

【问题讨论】:

标签: javascript reactjs react-router query-string


【解决方案1】:

例如,您可以通过将 console.log 放入 componentDidMount 来轻松检查它,但鉴于 React 的工作原理,我相信它会像您所怀疑的那样卸载/安装。所以更好的解决方案是使用 react-router 也提供的history.replace() API:

private updateURL(date: Date){
  this.props.history.replace(`/?date=${formatDate(date)}`);
}

【讨论】:

  • 所以我必须用withRouter(...) 包装任何想要更新 URL 栏的组件,对吧?
  • 为了得到history对象?是的,或者从父组件传下来。您传递给 Route 组件的组件(如 &lt;Route component={MyComponent} /&gt;)默认具有 history 属性
猜你喜欢
  • 2018-12-06
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 2021-04-23
  • 2017-12-16
  • 2021-02-25
  • 2023-03-05
  • 1970-01-01
相关资源
最近更新 更多