react.js - React 如何监听路由变化重新渲染组件
本文介绍了react.js - React 如何监听路由变化重新渲染组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
// route.js
<Router>
<Switch>
<Route path="/" component={NewsList} />
<Route path="/new" component={NewsList} />
<Route path="/show" component={NewsList} />
<Route path="/ask" component={NewsList} />
<Route path="/jobs" component={NewsList} />
</Switch>
</Router>
class NewsList extends Component {
componentWillMount () {
const type = this.props.location.pathname.replace('/', '') || 'top'
this.props.dispatch(fetchListData(type))
}
render () {
...
}
}
react: v15.6.1
react-router: v4.1.1
部分代码如上,现在的问题是切换路由时,组件并不会重新渲染。请问如何解决?
解决方案
为什么需要重新渲染组件?实质上,你想要的只是当路由变化,请求对应路由的数据而已。
那么考虑一下React组件的生命周期钩子。第一次加载时:
"constructor"
"componentWillMount"
"render"
"componentDidMount"
当组件的props发生改变时,组件更新,会调用如下的生命周期钩子
"componentWillReceiveProps"
"shouldComponentUpdate"
"componentWillUpdate"
"render"
"componentDidUpdate"
当路由变化时,即组件的props发生了变化,会调用componentWillReceiveProps等生命周期钩子
那我们所需要做的只是: 当路由改变时,根据路由,也去请求一下数据就OK了,于是乎:
class NewsList extends Component {
componentDidMount () {
this.fetchData(this.props.location);
}
fetchData(location) {
const type = location.pathname.replace('/', '') || 'top'
this.props.dispatch(fetchListData(type))
}
componentWillReceiveProps(nextProps) {
if (nextProps.location.pathname != this.props.location.pathname) {
this.fetchData(nextProps.location);
}
}
render () {
...
}
}
这篇关于react.js - React 如何监听路由变化重新渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文