博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[React] Understanding setState in componentDidMount to Measure Elements Without Transient UI State
阅读量:5286 次
发布时间:2019-06-14

本文共 1944 字,大约阅读时间需要 6 分钟。

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 = {      width: 0,      height: 0    };  }  componentDidMount() {    const { width, height } = this.r.getBoundingClientRect();    this.setState({      width,      height    });  }  render() {    console.count("render");    return (      

(this.r = r)}> {
this.state.width} x {
this.state.height}

); }}render(
, document.getElementById("root"));

 

转载于:https://www.cnblogs.com/Answer1215/p/8511330.html

你可能感兴趣的文章
range()函数
查看>>
cs20_3-3
查看>>
codevs1074 食物链
查看>>
少量标签下的模型
查看>>
17.python购物车程序作业
查看>>
lightoj 1027【数学概率】
查看>>
Apparmor——Linux内核中的强制访问控制系统
查看>>
HOJ-1005 Fast Food(动态规划)
查看>>
jQuery 杂项方法
查看>>
系出名门Android(4) - 活动(Activity), 服务(Service), 广播(Broadcast), 广播接收 器(BroadcastReceiver)...
查看>>
Dynamics CRM Microsoft SQL Server 指定的数据库具有更高的版本
查看>>
FasfDFS整合Java实现文件上传下载
查看>>
love2d教程5--摄相机1视角跟随玩家
查看>>
用Hadoop构建电影推荐系统
查看>>
Linux命令1——a
查看>>
紫书 悲剧文本(链表)
查看>>
[读码时间] 弹出层效果
查看>>
session退出页面
查看>>
telnet登录路由器启动服务的shell脚本
查看>>
HSRP 详解
查看>>