【问题标题】:React - Component Will Mount not getting called when changing routes?React - 更改路由时不会调用组件安装?
【发布时间】:2017-06-25 09:18:23
【问题描述】:

当从 indexRoute 更改为路径为 ':topic' 的 Route 时,页面保持不变。

我的路线如下所示:

ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
  <Route path='/' addHandlerKey={true} component={App}>
    <IndexRoute component={ArticleList} />
    <Route path='/:topic'  component={ArticleList} />
    <Route path='/:id' component={Article} />
  </Route>
</Router>
</Provider>, document.getElementById('app'));

文章列表如下所示:

const _ArticleList = React.createClass({

componentWillMount () {
  this.props.fetchArticles();
},

render () {
  return (
  <div id='ArticleList' className='box'>
     {this.props.articles.map(function (article, i) {
      return <ArticleCard id={article._id} key={i} title={article.title} votes={article.votes} />;
     })}
  </div>
 );
}

当我导航到路线然后刷新页面时,它会更改为我想要的,而不是直接导航到它时。

需要明确的是,url 正在改变(感谢 App 组件),所以 params.topic 正在改变,但组件没有重新渲染,所以 componentWillMount 没有被触发。 (已经尝试过 componentWillReceiveProps 但这没有用)

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    我在尝试使用 conponentWillMount() 时注意到了同样的行为——这是 componentWillMount() 的拼写错误。

    拼写错误没有触发任何警告或错误,当然也没有触发我打算调用的事件。

    【讨论】:

    • 用完美的拼写狂怒到深夜
    【解决方案2】:

    您遇到的问题是,一旦加载了索引页面,组件就会安装并且不会卸载,除非您一起更改为完全不同的路线。您只是在更新一个不会重新触发 componentWillMount 以再次触发的子路由。

    您需要重新访问componentWillReceiveProps,因为这是正确的做法。

    类似:

    componentWillReceiveProps(nextProps) {
     // in our own app we have acces to routeParams as the :id portion not sure if that works on your app
     // but idea should be if the topic has changed then refetch the articles 
    
    
      if (this.props.routeParams !== nextProps.routeParams) {
        this.props.fetchArticles();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 2017-06-10
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2018-02-05
      • 2020-01-22
      • 1970-01-01
      相关资源
      最近更新 更多