2016-03-21 74 views
2

目前我有兩個組件(一個容器組件和一個演示文件)。我有一些邏輯應該在componentDidMountcomponentWillReceiveProps生命週期方法中實施,特別是我必須在那裏發送一些操作。Redux。從容器組件描述表示組件的生命週期方法

現在,我映射那些行動的創作者在mapDispatchToLinkProps功能,並傳遞給我的表象組件的propsconnect功能,事後,我給他們打電話componentDidMountcomponentWillReceiveProps方法。這裏是如何,我實現它:

容器組件

const mapDispatchToLinkProps = (dispatch, ownProps) => { 
    return { 
    onMount:() => { 
     dispatch(loadRooms(ownProps.floor)) 
    }, 
    onPropsReception: (nextProps, currentProps) => { 
     if (nextProps.floor != currentProps.floor) { 
     dispatch(loadRooms(nextProps.floor)) 
     } 
    } 
    } 
} 

表象成分:

export default connect(mapStateToProps, mapDispatchToLinkProps)(MapLayer): 

componentDidMount() { 
    this.props.onMount() 
} 

componentWillReceiveProps(nextProps) { 
    this.props.onPropsReception(nextProps, this.props) 
} 

render() { 
// ... 
} 

,我不喜歡這裏的事情,是我以這種方式丟失上下文,我必須通過this.props作爲第二個參數onPropsReception方法:

this.props.onPropsReception(nextProps, this.props) 

有沒有一種方法可以從容器組件描述表示組件的生命週期方法,但是保持表示組件的上下文?或者甚至更好,覆蓋生命週期方法而無需在表示組件中調用?

+1

你能解決這個問題嗎?我有類似的問題。我正在使用react路由器和redux。我正在捕捉url查詢參數(/ search?q ='foo'&page = 1)。當url參數更改時,將調用componentWillUpdate生命週期方法。我不知道使用connect方法傳遞生命週期組件的方式。或者,如果我如何將mapStateToProp傳遞給React.createClass組件。 –

+0

對不起,沒有時間回到這裏,沒有解決問題。 –

回答

0

對不起,我不能添加評論還,

爲什麼不這樣做你的表象成分&必要的檢查只是做一個電話後用正確的PARAMS?

例如:

componentWillReceiveProps(nextProps) { 
    if (this.props.floor != nextProps.floor) { 
    this.props.loadRooms(nextProps.floor); 
    } 
} 

的ContainerComponent:

const mapDispatchToLinkProps = (dispatch, ownProps) => { 
    return { 
    onMount:() => { 
     dispatch(loadRooms(ownProps.floor)) 
    }, 
    loadRooms: (floor) => { 
     dispatch(loadRooms(floor)); 
    } 
    } 
} 

什麼你問是可行的有一些黑客,但它違背了反應&終極版理念。

+0

謝謝你的回答,但我不這麼認爲。進行驗證:'if(this.props.floor!= nextProps.floor)'在表示組件中我正在實現一種數據行爲,但不應該在這裏完成。 現在我正在'connect'方法中尋找'mergeProps'參數。 Dan Abramov就如何在這裏使用它提供了一個非常好的解釋:https://github.com/reactjs/react-redux/issues/237#issuecomment-168816713 不過,謝謝你的回答! –