2017-06-19 22 views
0

由於帶有示例數據store.profiles商店:使用mapStateToProps,如何查找並設置特定的記錄?

[{"user_id":1,"stuff":"more stuff"},{"user_id":2,"stuff":"more stuff"},{"user_id":3,"stuff":"more stuff"}] 

我怎樣才能找到CURRENT_USER的特定記錄,並與mapStateToProps送呢?

const mapStateToProps = (state, ownProps) => ({ 
    item: XXXXXXXX 
}); 

其中xxxxxxxx是CURRENT_USER的ID(USER_ID = 1)

回答

1

您可以使用數組的find方法。如果stateprofile密鑰是一個數組只是這樣做:

const mapStateToProps = state => ({ 
    item: state.profiles.find(el => el.user_id === 1) 
}); 

然後在組件,您將有機會獲得的item道具:

this.props.item === {"user_id":1,"stuff":"more stuff"} 
+0

這是偉大的。謝謝...如果配置文件未定義,會出現此錯誤嗎?或者會在reducer中設置initialValue處理? – AnnaSm

+1

好問題。如果'profiles'是'undefined'或'user_id'不匹配,'find'將返回'undefined'。所以你必須自定義代碼來處理這些情況。 –

+0

謝謝,但你如何處理mapStateToProps中的未定義? – AnnaSm

相關問題