【问题标题】:Redux. Describe presentational component's lifecycle methods from a container component还原。从容器组件描述展示组件的生命周期方法
【发布时间】:2016-03-21 15:30:40
【问题描述】:

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

现在,我将这些动作创建者映射到 mapDispatchToLinkProps 函数中,并使用 connect 函数将它们传递给我的演示组件的 props,然后,我在 componentDidMount 和 @ 中调用它们987654327@ 方法。以下是我的实现方式:

容器组件

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)

有没有办法从容器组件中描述展示组件的生命周期方法,但保留展示组件的上下文?或者更好的是,覆盖生命周期方法而不在展示组件中进行任何调用?

【问题讨论】:

  • 你能解决这个问题吗?我有类似的问题。我正在使用反应路由器和 redux。我正在捕获 url 查询参数(/search?q='foo'&page=1)。 url 参数更改时调用 componentWillUpdate 生命周期方法。我不知道使用 connect 方法传递生命周期组件的方法。或者,如果我如何将 mapStateToProp 传递给 React.createClass 组件。
  • 抱歉,没有时间回到这里,问题没有解决。

标签: javascript reactjs redux


【解决方案1】:

抱歉,我还不能添加评论,

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

例如:

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));
    }
  }
}

你的问题可以通过一些 hack 来实现,但这违背了 react 和 redux 的理念。

【讨论】:

  • 感谢您的回答,但我不这么认为。进行此验证:if (this.props.floor != nextProps.floor) 在演示组件中我正在实现一种数据行为,但不应该在这里完成。现在我正在寻找 connect 方法中的 mergeProps 参数。 Dan Abramov 在这里对如何使用它提供了很好的解释:github.com/reactjs/react-redux/issues/… 不过,感谢您的回答!
猜你喜欢
  • 2016-09-05
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多