1

我正在尝试创建一个包装器 HOC,我可以在其中选择要传递的生命周期挂钩。我尝试了以下 HOC:

const HOC = lifeCycleHook => WrappedComponent => {
  return class OriginalComponent extends React.Component {
    lifeCycleHook
    render(){
      return (
        <WrappedComponent {...this.props} />
      );
    }
  }
}

export default HOC;

用于包装原始组件的组件:

import React from 'react';
import HOC from './helpers/hoc';
import componentDidMount from './helpers/componentDidMount';

const Home = () => <h1>Home</h1>;

export default HOC(componentDidMount)(Home);

最后是生命周期钩子:

import React from 'react';

function componentDidMount(){
  console.log('Test')
}

export default componentDidMount;

编辑:没有编译错误被抛出,但控制台日志不会触发打印“测试”

4

1 回答 1

3

recompose软件包可以为您做到这一点。这是lifecycle助手的示例:

const PostsList = ({ posts }) => (
  <ul>{posts.map(p => <li>{p.title}</li>)}</ul>
)

const PostsListWithData = lifecycle({
  componentDidMount() {
    fetchPosts().then(posts => {
      this.setState({ posts });
    })
  }
})(PostsList);
于 2019-05-17T13:39:15.383 回答