[英]React Native receving new props, componentWillReceiveProps
[英]mapStateToProps gets new props but unable to invoke componentWillReceiveProps
我正在使用React:16+和react-redux:6+
我連線了所有的動作和減速器。 而且,只需單擊一個按鈕,我就可以調用mapStateToProps(),但是在此之后,未調用componentWillReceiveProps或shouldComponentUpdate。
這是我的代碼:
class HeaderContainer extends React.Component { constructor(props) { super(); this.props = props; this.state = { headerBtn: [] } } componentWillReceiveProps(nextProps){ console.log(nextProps); } render() { return ( <HeaderComponent className="flx-n-grow" headerBtns={this.props.headerBtns} selectExchange={this.props.selectExchange}/> ) } } const mapStateToHeaderProps = (state) => { console.log("received new props"); console.log(state); console.log(state.HeaderReducer.headerBtns); return { headerBtns : state.HeaderReducer.headerBtns } } const mapDispatchToHeaderProps = (dispatch) => { return { selectExchange: (exchanges, exchange) => { dispatch(HeaderAction.selectExchange(exchanges, exchange)); } } } export default connect(mapStateToHeaderProps, mapDispatchToHeaderProps)(HeaderContainer);
mapStateToProps內部的所有console.log都將被調用,但是componentWillReceiveProps或shouldComponentUpdate永遠不會被調用。
constructor(props) {
super();
this.props = props;
this.state = {
headerBtn: []
}
}
嘗試將道具添加到超級
super(props);
經過24小時的POC和調試后,事實證明,盡管使用了傳播運算符,但我的reducer並未返回新對象:
let newState = {...state};
newState.name = ...
因此,我從Internet上閱讀的內容以及Redux專門對文檔進行故障排除的內容是,如果狀態發生變化,則不會調用mapStateToProps。 這似乎不正確。 就我而言,或者在任何狀態突變的情況下,Redux都會調用mapStateToProps。 它根本不會調用shouldComponentUpdate()。
被傳播者之所以只能淺拷貝對象。 因此,如果對象中存在嵌套的對象,則散布運算符將保留該對象的引用,因此,一旦內部對象更新,原始狀態就會發生變化。 為避免此類情況,請始終使用可深深復制對象的任何工具。
_.cloneDeep(stateCopy, stateInitial)
就我而言。
順便說說,
console.log(newState === state)
返回false,表示該狀態未發生突變,實際上是一個克隆狀態。 很奇怪。 :(
不要使用傳播運算符。 它不會做深層復制。 僅在狀態具有簡單鍵/值對的情況下才有用。 對於嵌套在對象中的復雜對象,散布運算符將嚴重失敗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.