查询字符串更改时更新React组件

时间:2019-03-21 20:58:46

标签: javascript reactjs react-router query-string

当另一个组件更改查询/搜索字符串时,我需要一个组件来重新呈现。

要更改我正在使用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而更改时,是否会导致边栏更新?

1 个答案:

答案 0 :(得分:1)

例如,您可以通过将public getSelectChoosed(_selectType: string): HTMLSelectElement { switch(_selectType) { case 'select-one': return this.__selectOne; case 'select-two': return this.__selectTwo; default: console.warn('DO NOT EXIST THIS SELECT ON THE COMPONENT!'); break; } } 放在console.log中来轻松地检查它,但是鉴于React的工作原理,我相信它将如您所愿地卸载/装载。因此,更好的解决方案是使用react-router还提供的componentDidMount API:

history.replace()