路线改变后刷新组件

问题描述 投票:0回答:2

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

 <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()调用但没有做任何事情。任何帮助表示赞赏!

reactjs react-router mobx
2个回答
0
投票

这是因为您的组件已经渲染,并且没有看到任何更改,因此它不会重新渲染。

您必须使用componentWillReceiveProps方法强制刷新组件

componentWillReceiveProps(nextProps){
   if(nextProps.match.params.topic){
      //Changing the state will trigger the rendering
      //Or call your service who's refreshing your data
      this.setState({
        topic:nextProps.match.params.topic
      })
   }
}

编辑

componentWillReceiveProps方法已弃用。现在,当源数据来自道具参数时,静态getDerivedStateFromProps是首选

Documentation

此方法应返回触发重新挂载的新状态,或者为无刷新返回null。

  static getDerivedStateFromProps(props, state) {
    if (props.match.params.topic && props.match.params.topic !== state.topic) {
      //Resetting the state
      //Clear your old data based on the old topic, update the current topic
      return {
        data: null,
        topic: props.match.params.topic
      };
    }
    return null;
  }

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.