【问题标题】:React Component not support lifecycle methods?React Component 不支持生命周期方法?
【发布时间】:2019-03-02 11:23:07
【问题描述】:

如何在下面的函数中使用生命周期方法,例如 ComponentDidMount?

var React = require('react');

module.exports = function SectionalSquareComponent(props) {


  return (
    <div .....

【问题讨论】:

标签: reactjs


【解决方案1】:

如果你想使用生命周期功能,你需要扩展 React.Component 类。正如@xadm 提到的,您不能使用功能组件和生命周期挂钩。

使用问题中的 ES5 语法,可能如下所示:

var createReactClass = require('create-react-class');
module.exports = createReactClass({
  componentDidUpdate: function(prevProps, prevState) {
  },
  render: function() {
    return (<div>...</div>);
  }
});

【讨论】:

    【解决方案2】:

    正如其他人所说,如果您想挂钩生命周期方法,则需要使用 react.component

    如果您完全专注于功能组件,一个有趣的替代方法是使用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);
    

    【讨论】:

    • 为什么要导入额外的依赖项来实现这一点,而不是遵循 React 的“方式”让有状态/类组件挂钩到生命周期方法而不是无状态/功能组件?
    • 你不会的,它只是一个有趣的替代品和相对有用的库
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    相关资源
    最近更新 更多