React 如何监听路由变化重新渲染数据
条评论应用场景:1
2
3
4
5
6
7
8
9
10// route.js
<Router>
<Switch>
<Route path="/" component={NewsList} />
<Route path="/a" component={NewsList} />
<Route path="/b" component={NewsList} />
<Route path="/c" component={NewsList} />
<Route path="/d" component={NewsList} />
</Switch>
</Router>
1 | class NewsList extends Component { |
分析:
React组件的生命周期钩子。第一次加载时:1
2
3
4"constructor"
"componentWillMount"
"render"
"componentDidMount"
当组件的props发生改变时,组件更新,会调用如下的生命周期钩子1
2
3
4
5"componentWillReceiveProps"
"shouldComponentUpdate"
"componentWillUpdate"
"render"
"componentDidUpdate"
当路由变化时,即组件的props发生了变化,会调用componentWillReceiveProps等生命周期钩子
怎么做呢?1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20class 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 () {
...
}
}