使用 react-redux connect 响应 onComponentDidMount 事件
React onComponentDidMount event with react-redux connect
在下面的示例中,onComponentDidMount 不起作用,因为 React 中不存在该事件。假设我不想使用 React.Component 重写 Main,我应该使用什么事件,或者有其他方法吗?
let Main = ({myEventMethod}) => (
<main onComponentDidMount={myEventMethod}>
...
</main>
)
const mapDispatchToProps = (dispatch) => ({
myEventMethod: () => {...}
})
Main = connect(null, mapDispatchToProps)(Main)
Stateless Functions do not have the component lifecycle methods.
高阶组件来拯救。 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)
在下面的示例中,onComponentDidMount 不起作用,因为 React 中不存在该事件。假设我不想使用 React.Component 重写 Main,我应该使用什么事件,或者有其他方法吗?
let Main = ({myEventMethod}) => (
<main onComponentDidMount={myEventMethod}>
...
</main>
)
const mapDispatchToProps = (dispatch) => ({
myEventMethod: () => {...}
})
Main = connect(null, mapDispatchToProps)(Main)
Stateless Functions do not have the component lifecycle methods.
高阶组件来拯救。 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)