在下面的示例中, onComponentDidMount 不起作用,因为React中不存在该事件。假设我不想使用React.Component重写Main,我应该使用什么事件,还是有其他方式?
let Main = ({myEventMethod}) => (
<main onComponentDidMount={myEventMethod}>
...
</main>
)
const mapDispatchToProps = (dispatch) => ({
myEventMethod: () => {...}
})
Main = connect(null, mapDispatchToProps)(Main)
答案 0 :(得分:0)
无状态函数没有组件生命周期方法。
答案 1 :(得分:0)
高阶组件来救援。 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)