2016-01-03 21 views
1

我使用React Router + Redux,當我嘗試加載嵌套視圖(嵌套視圖在ReactTransitionGroup中)時,它正確加載,但它沒有正確加載,不會觸發任何特殊的鉤子,如「ComponentWillEnter」或「ComponentWillLeave」。React Router + Redux + Transition組沒有觸發特殊的生命週期鉤子

在添加Redux「連接」之前,它正常工作。

我的路線是這樣的

<Route path="lists" component={Lists}> 
     <Route path="listsA" component={ListsA}/> 
     <Route path="listsB" component={ListsB}/> 
</Route> 

我的部件

列表

@connect(..) 
class Lists extends React.Component { 
    ... 
    render(){ 
     const { pathname } = this.props.location; 
     const key = pathname.split('/') || 'Lists'; 
     const element = this.props.children || <div/>; 
     const messages = this.props.messages; 
     const elementToAnimate = React.cloneElement(element, { key, messages }); 

     return <div className="lists-wrapper"> 
      <div className="nested-views"> 
       <ReactTransitionGroup> 
        {elementToAnimate} 
       </ReactTransitionGroup> 
      </div> 
     </div> 
    } 
} 

ListsA/ListsB

@connect(..) 
    class ListsA extends React.Component { 
     ... 
     render(){ 
      ... 
      } 
    } 

我並沒有寫太多的代碼,因爲我是 不知道問題出在哪裏,如果你需要我添加更多的代碼,我完全可以。

回答

0

所以昨晚我也經歷過這個問題,這裏是我發現它的工作原理。

首先出現的是這種方法https://github.com/reactjs/react-redux/issues/101 在這裏您可以與處理特殊的生命功能的包裝紙包住連接組件,並通過道具來你的連接組件。

或者

你可以通過「withRef」標誌連接,並從連接組件調用這些生命週期功能,隨後有打電話給你的組件生命週期功能。 我把它包裝成一個包,你可以放在連接前。

// npm install --save connect-with-transition-group 
// https://github.com/esayemm/connect-with-transition-group 

import React, { Component, PropTypes } from 'react'; 
import { connect } from 'react-redux' 
import connectWithTransitionGroup from 'connect-with-transition-group'; 

class Foo extends Component { 
    // ... 

    componentWillEnter(cb) { 
    // this works! 
    cb(); 
    } 

    // ... 
} 

export default connectWithTransitionGroup(connect(
    mapStateToProps, 
    null, 
    null, 
    // IMPORTANT: must pass this flag to react-redux/connect 
    { 
    withRef: true, 
    } 
)(Foo));