首页 > 解决方案 > 路由更改后刷新组件

问题描述

我有一排按钮,所有链接到正在呈现的图表,然后按下按钮,它决定哪些数据将显示在下面的图表上。

 <div>
    <Route path="/" component={Main} />
    <Route path="/chart/:topic" component={Chart} />
 </div>

按钮元素:

<Link to={"/chart/" + collection.name}>
      <Button key={index} data-key={index} style={this.btnStyle}>
        {this.store.capitalizeFirstLetter(collection.name)}
      </Button>
</Link>

第一次按下按钮时,这工作正常。但是,如果用户尝试通过按下不同的按钮来更改数据,图表组件根本不会刷新,浏览器会显示 URL 已更改,但组件根本不会刷新。

我知道这是因为,我在图表组件中放置了一个 console.log 并且在第二次按下按钮时它没有出现。

componentDidMount = () => {
   const { match: { params } } = this.props;
   this.topic = params.topic;
   console.log("chart topic", this.topic);
   this.refreshData(true);
   this.forceUpdate();
   this.store.nytTest(this.topic, this.startDate, this.endDate);
};

如您所见,我尝试调用 forceUpdate() ,但什么也没做。任何帮助表示赞赏!

标签: reactjsreact-routermobx

解决方案


componentDidMount仅在安装(渲染)组件时调用一次。您应该使用getDerivedStateFromProps来更新您的组件


推荐阅读