0

我正在使用 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

我的问题是,

  1. 在考虑应用程序性能时,最好的方法是什么?
  2. 我也可以使用相同的方法mapDispatchToProps吗?
4

2 回答 2

1

是的,你可以使用useSelector, useDispatch,但问题是你应该使用钩子。它可以通过这种方法解决考虑应用程序性能的问题。

于 2021-06-05T06:58:34.973 回答
1

我认为与其使用“const”,不如尝试其他数据类型,例如“var”或“let”,因为一旦固定就无法更改“const”值。

于 2021-06-05T07:00:57.707 回答