雷杜克斯.从容器组件描述表示组件的生命周期方法

Redux. Describe presentational component's lifecycle methods from a container component

本文关键字:组件 表示 描述 生命 方法 周期 杜克 雷杜克      更新时间:2023-09-26

目前我有两个组件(一个容器组件和一个演示组件)。我有一些逻辑应该在componentDidMountcomponentWillReceiveProps生命周期方法中实现,特别是我必须在那里调度一些操作。

现在,我正在mapDispatchToLinkProps函数中映射这些动作创建者,并使用connect函数将它们传递给表示组件的props,然后,我在componentDidMountcomponentWillReceiveProps方法中调用它们。以下是我如何实现它:

容器组件

const mapDispatchToLinkProps = (dispatch, ownProps) => {
  return {
    onMount: () => {
      dispatch(loadRooms(ownProps.floor))
    },
    onPropsReception: (nextProps, currentProps) => {
      if (nextProps.floor != currentProps.floor) {
        dispatch(loadRooms(nextProps.floor))
      }
    }
  }
}

表现组件:

export default connect(mapStateToProps, mapDispatchToLinkProps)(MapLayer):
componentDidMount() {
    this.props.onMount()
}
componentWillReceiveProps(nextProps) {
  this.props.onPropsReception(nextProps, this.props)
}
render() {
// ...
}
我不喜欢这里的事情是,我以

这种方式丢失了上下文,我必须this.props作为第二个参数传递给onPropsReception方法:

this.props.onPropsReception(nextProps, this.props)

有没有办法从容器组件描述表示组件的生命周期方法,但保留表示组件的上下文?或者更好的是,在表示组件中没有任何调用的情况下重写生命周期方法?

抱歉,

我还不能添加评论,

为什么不在表示组件中进行必要的检查,然后使用正确的参数进行调用?

前任:

componentWillReceiveProps(nextProps) {
  if (this.props.floor != nextProps.floor) {
    this.props.loadRooms(nextProps.floor);
  }
}

容器组件 :

const mapDispatchToLinkProps = (dispatch, ownProps) => {
  return {
    onMount: () => {
      dispatch(loadRooms(ownProps.floor))
    },
    loadRooms: (floor) => {
        dispatch(loadRooms(floor));
    }
  }
}

你所要求的是可以通过一些黑客来实现的,但它违背了反应和redux的哲学。