[英]Eliminating redundancy between different mapStateToProps
我的redux商店具有以下結構:
{ A: {item1, item2, item3},
.....
F : {item1, item2, item3},
a : {anotherItem1, anotherItem2}
.....
z : {anotherItem1, anotherItem2}
}
也就是說,它是平坦的,並且特性具有規范化的結構。 問題是我有大約8個不同的屏幕,其中許多屏幕都希望從這些屬性中訪問大量特定項。 這意味着我的許多mapStateToProps
函數都有冗余代碼。
例如,假設Screen1如下定義mapStateToProps
mapStateToProps(state){
aitem1 : stata.a.item1,
aFormatted : formatFunction(state.a.item2, state.a.item3)
bitem1: state.b.item1,
bFormatted : formatFunction(state.b.item2, state.b.item2)
...
}
現在,假設Screen2還希望為其道具賦予完全相同的狀態以及其他一些屬性。 然后,Screen2應該具有這樣的mapStateToProps函數
mapStateToProps(state){
aitem1 : stata.a.item1,
aFormatted : formatFunction(state.a.item2, state.a.item3)
bitem1: state.b.item1,
bFormatted : formatFunction(state.b.item2, state.b.item2)
...
other stuff
}
如果屏幕3和4也需要相同的內容,則問題只會進一步惡化。 那么如何避免這個問題呢?
您可以編寫一個單獨的函數來選擇狀態的特定部分,然后在mapStateToProps
函數中調用該函數:
const getDataParts = state => ({
foo: state.foo,
bar: state.baz,
});
然后在mapStateToProps
像這樣使用它:
const mapStateToProps = state => ({
...getDataParts(state),
otherProp: state.someOtherProp,
});
編輯 :
請注意, 每次狀態更改時都可能調用mapStateToProps
。 如果選擇器進行任何計算,它將為該組件創建新的道具,即使計算結果相同,該道具也會重新渲染。 為了避免這種情況,您必須使用記憶選擇器,例如庫reselect
提供。
有關進一步的說明和示例,請參見《 慣用的Redux:使用重新選擇選擇器進行封裝和性能》 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.