我正在使用 redux 状态管理创建反应本机应用程序。我想知道连接(mapStateToProps,mapDispatchToProps)的最佳实践是什么。
我有几个组件类,即 ParentA、ChildA、ChildB。目前,我正在独立获取每个父类和子类的状态属性。
例如:
const ParentA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
<ChildA />
<ChildB />
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ParentA)
const ChildA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ChildA)
const ChildB = (props) => {
return (
<View>
<Text>{props.item.age}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ChildB)
但是connect
对于每个子组件,我可以从中获取item
状态ParentA
并将其传递给Child
组件。
例如:
const ParentA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
<ChildA item={item}/>
<ChildB item={item}/>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default connect(mapStateToProps)(ParentA)
const ChildA = (props) => {
return (
<View>
<Text>{props.item.name}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default ChildA
const ChildB = (props) => {
return (
<View>
<Text>{props.item.age}</Text>
</View>
)
}
const mapStateToProps = (state) => {
const { item } = state
return {
item: item.item,
}
}
export default ChildB
我的问题是,
- 在考虑应用程序性能时,最好的方法是什么?
- 我也可以使用相同的方法
mapDispatchToProps
吗?