访问发送到组件的 props 以及 Redux 状态数据

Access props sent to components along with Redux state data

通常您可以在子组件上访问父组件发送给子组件的道具。但是,当在子组件上使用 redux 时,父组件发送的 props 会因使用 'connect' 方法而丢失,该方法将 redux 状态映射到组件 props。

例如:

正在声明具有属性的组件: <A_Component prop1='1' prop2='2' />

在没有 redux 的情况下访问子组件,工作正常: this.props.prop1this.props.prop2

如果使用 redux 状态,相同的语句将给出 undefined 错误。

自己的组件道具可用作 mapStateToProps 函数的第二个参数:

// ParentComponent.js

// ... other component methods ...
render() {
  return <TodoContainer id="1" />
}

// TodoContainer.js

// `ownProps` variable contains own component props
function mapStateToProps(state, ownProps) {
  return {
    todo: state.todos[ownProps.id]
  };
}

react-redux connect method 将道具传递给包装元素。 connect方法可以接收3个方法:

  • mapStateToProps - 创建数据道具
  • mapDispatchToProps - 创建动作道具
  • mergeProps - 结合前面两种方法产生的道具, 并添加父分配道具(ownProps / parentProps)。

通常您只覆盖 mapStateToProps 和或 mapDispatchToProps,并使用默认的 mergeProps (defaultMergeProps).

这是defaultMergeProps方法的定义:

const defaultMergeProps = (stateProps, dispatchProps, parentProps) => ({
  ...parentProps, // ownProps
  ...stateProps, // mapStateToProps
  ...dispatchProps // mapDispatchToProps
})

因此,除非您用自己的 mergeProps 方法覆盖 defaultMergeProps,否则您将始终获得父级分配的 props。

顺便说一句 - mapStateToPropsmapDispatchToProps 也接收 ownProps,因此他们可以将它们与状态结合起来,并创建新的数据道具/动作道具。