简体   繁体   English

使用react-redux connect反应onComponentDidMount事件

[英]React onComponentDidMount event with react-redux connect

In the below example, onComponentDidMount does not work because that event does not exist in React. 在以下示例中, onComponentDidMount不起作用,因为该事件在React中不存在。 Assuming I don't want to rewrite Main using React.Component, what event should I use, or is there another way? 假设我不想使用React.Component重写Main,我应该使用哪个事件,或者还有另一种方法?

let Main = ({myEventMethod}) => (
    <main onComponentDidMount={myEventMethod}>
        ...
    </main>
)

const mapDispatchToProps = (dispatch) => ({
    myEventMethod: () => {...}
})

Main = connect(null, mapDispatchToProps)(Main)

DOCS: DOCS:

Stateless Functions do not have the component lifecycle methods. 无状态函数没有组件生命周期方法。

Higher Order Components come to rescue. 高阶组件来营救。 Demo . 演示

const withComponentDidMount = handler => Cmp => {
  class WithComponentDidMount extends Component {
    render() {
      return <Cmp {...this.props}/>
    }
  }

  WithComponentDidMount.prototype.componentDidMount = handler

  return WithComponentDidMount
}

const Wrapped = withComponentDidMount(function() {
  console.log('Mount')
})(App)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM