我有一排按钮,所有按钮都链接到正在渲染的图表,然后按下按钮,它决定哪些数据将显示在下面的图表上。
<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()调用但没有做任何事情。任何帮助表示赞赏!
这是因为您的组件已经渲染,并且没有看到任何更改,因此它不会重新渲染。
您必须使用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
是首选
此方法应返回触发重新挂载的新状态,或者为无刷新返回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;
}
componentDidMount
仅在安装(渲染)组件时调用一次。您应该使用getDerivedStateFromProps
更新您的组件