componentDidUpdate 与 componentDidMount [英] componentDidUpdate vs componentDidMount

查看:115
本文介绍了componentDidUpdate 与 componentDidMount的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当满足以下条件时,我需要确保输入元素获得焦点:

I need to make sure an input element is focused when the following is true:

  • DOM 可用并且
  • 属性已更改

问题:我需要将我的代码同时放在 componentDidUpdatecomponentDidMount 中,还是只需要 componentDidUpdate 就足够了?

Question: Do I need to put my code in both componentDidUpdate and componentDidMount or just componentDidUpdate would be suffice?

    private makeSureInputElementFocused() {
        if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
            this.inputElement.focus();
        }

    }

    componentDidMount() {
        this.makeSureInputElementFocused(); // <-- do i need this?
    }
    componentDidUpdate() {
        this.makeSureInputElementFocused();
    }

推荐答案

您必须同时使用两者.

componentDidMount()

componentDidMount() 在组件安装后立即调用.需要 DOM 节点的初始化应该在这里进行.如果您需要从远程端点加载数据,这是实例化网络请求的好地方.在此方法中设置状态将触发重新渲染.

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

componentDidUpdate()

componentDidUpdate() 在更新发生后立即调用.初始渲染不会调用此方法.

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

您也可以将它放入 render() 方法中,这似乎适合您的情况,因为您总是想检查焦点.那么你就不需要把它放入componentDidMount()componentDidUpdate()

You also could place it into the render() method which seems like it's appropriate for your case since you always want to check the focus. Then you don't need to put it into componentDidMount() and componentDidUpdate()

这篇关于componentDidUpdate 与 componentDidMount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆