【发布时间】:2016-03-21 15:30:40
【问题描述】:
目前我有两个组件(一个容器组件和一个演示文稿)。我有一些应该在componentDidMount 和componentWillReceiveProps 生命周期方法中实现的逻辑,特别是我必须在那里调度一些操作。
现在,我将这些动作创建者映射到 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