React-router-dom 路由切换时,如何触发 componentDidMount?

#1

最近学了一些 react 和 redux 的知识,打算在项目中使用,以往看教程的时候,讲师都是将获取ajax数据放在 componentDidMount 里面做的。但是这样的话组件只在初始的时候调用。
而有些路由类似于:

<Route path='/detail/:id' component={detail} />

然后我有一些 用于跳转的

<Link to="/detail/123"></Link>  <Link to="/detail/456"></Link>

componentDidMount(){
    const { match,handleAjaxItem } = this.props;
    handleAjaxItem(match.params.id);
  }
  render(){
    const { item } = this.props;
    return(
      <div className="site-content">
        <div className="container">
          <Item item={item}/>
       </div>
      </div>
    )
  }

首次进入页面例如 detail/123 的时候是没问题,但往后切换到 detail/456 ,就没办法了。
请教这种情况,在不使用其他生命周期的情况下,如何处理呀?

#2

这是因为你这两个对应的都是一个detail组件,需要用key将组件加以区分,我的方法是用函数把组件包装一下
例如

// 这是正常的导出组件
export default Detail;

// 用函数包装一下变成这样
export default function(props) {
    return <Detail {...props} key={props.id}/>
}
1 Like
#3

componentWillReceiveProps

#4

用生命周期componentWillReceiveProps是我见过更常用的做法,楼主为啥不想用生命周期

#5

大神,请受小弟一拜