zoukankan      html  css  js  c++  java
  • [React] Understanding setState in componentDidMount to Measure Elements Without Transient UI State

    In this lesson we'll explore using setState to synchronously update in componentDidMount. This allows for us to use getBoundingClientRect or other synchronous UI calls and make changes to the UI without a transient UI state.

    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.

    This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

    Calling setState() in this method will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.

    That being said, using setState in componentDidMount:

    • which is good for fetching data from API.
    • which is good for Modal and tooltip component which related to position.
    • because render() functions is called twice, be careful about proferemce issue.
    import React, { Component } from "react";
    import { render } from "react-dom";
    
    class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
           0,
          height: 0
        };
      }
      componentDidMount() {
        const { width, height } = this.r.getBoundingClientRect();
        this.setState({
          width,
          height
        });
      }
      render() {
        console.count("render");
        return (
          <div>
            <h2 ref={r => (this.r = r)}>
              {this.state.width} x {this.state.height}
            </h2>
          </div>
        );
      }
    }
    
    render(<App />, document.getElementById("root"));
  • 相关阅读:
    operamasks—omMessageBox的使用
    operamasks-omGrid的使用
    SQL Server转sqlite数据库
    operamasks—omMessageTip的使用
    operamasks—omBorderLayout布局
    选择器(E:hover/E:active/E:focus的使用)
    CSS3(各UI元素状态伪类选择器受浏览器的支持情况)
    选择器的使用(nth-of-type和nth-last-of-type选择器)
    选择器的使用(nth-child和nth-last-child选择器)
    选择器的使用(first-child和last-child选择器)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8511330.html
Copyright © 2011-2022 走看看