【问题标题】:What are some tips on refactoring lifecycle component methods into useEffect hook?将生命周期组件方法重构为 useEffect 钩子有哪些技巧?
【发布时间】:2022-01-06 22:56:27
【问题描述】:

我正在尝试将以下内容重构为 ES6 作为功能组件。我考虑研究 lodash 装饰器:https://www.npmjs.com/package/lodash-decorators#bind,但是有没有关于将这样的类组件重构为符合 ES6 的功能组件的技巧,尤其是当生命周期组件方法中的逻辑变得更加复杂时?

constructor(props) {
        super(props);
        this._isMounted = false;
        this.state = {
            profilePictureFailedToLoad: false,
   
        };
        if (process.browser) {
            this.profileImage = new Image();
            this.profileImage.src = this.props.userInfo.userAssetUrl;
        }
        this.handleLoginClick = this.handleLoginClick.bind(this);
        this.handleLogoutClick = this.handleLogoutClick.bind(this);
        this.handleProfileClick = this.handleProfileClick.bind(this);
        this.handleModalClose = this.handleModalClose.bind(this);
        this.handleDeleteAccountClick = this.handleDeleteAccountClick.bind(this);
        this.handleDeleteAccountModalClose = this.handleDeleteAccountModalClose.bind(this);
    }

    componentDidMount() {
        this._isMounted = true;
    }

    componentDidUpdate(prevProps) {
        if (this.props.router.query.login === "true" && prevProps.router.query.login !== "true") {
        console.log("Updating...")
        }
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

【问题讨论】:

    标签: reactjs typescript refactoring


    【解决方案1】:

    伊甸园。

    我认为代码是生产代码的抽象。对?一个真实的代码示例会更容易,但让我们尝试提供帮助:

    从类组件到带有钩子的函数组件一开始并不容易想象。

    _isMounted 标志。

    我不知道该标志是如何使用的,但您可能不需要它。如果你这样做了,你可以在 + useEffect 里面使用一个 useRef;

    我必须强调你可能不需要这个实现:

    const ref = React.useRef(false);
    
    React.useEffect(() => {
        // This will run only in the first render;
        ref.current = true;
        () => {
            ref.current = false;            
        }
    }, [])
    

    componentDidUpdate

    如果您需要渲染加载而不是那个console.log,您可以将此逻辑移动到函数组件的返回(渲染)部分。

    处理程序

    您可能可以将它们附加到每个对应的元素。如果这对您有意义,您可以使用 React.useCallback 来避免重新渲染子组件。

    个人资料图片

    那将如何使用?我也相信这可以配合渲染部分。

    希望能给你一些好的方向。

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 2021-03-27
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      相关资源
      最近更新 更多