Table of Contents
Container component and presentational component
Props, State and the common properties of the component
setState Asynchronousness
componentWillReceiveProps
shouldComponentUpdate
render
如何发送网络请求
Home Web Front-end JS Tutorial How much do you know about react? Summary of things to note about react

How much do you know about react? Summary of things to note about react

Sep 11, 2018 am 11:23 AM
react web front end

This article mainly talks about things you need to know about react, such as container components, component properties, setState asynchrony, etc. Let us take a look at this article together. Article Bar


Container component and presentational component

When using React to write components, we need to consciously combine the components Divided into container components and presentational components, this helps us to be more clear about what this component should be responsible for when writing components.

Container components are responsible for processing business process logic, such as sending network requests, processing request data, and passing the processed data to the Props of sub-components for use. At the same time, the container component provides methods of source data and passes them to sub-components in the form of Props. When the state changes of the sub-component cause changes in the source data, the sub-component synchronizes these changes by calling the methods provided by the container component.

Display components are responsible for the appearance of the component, that is, how the component is rendered, and have strong cohesion. The presentational component does not care how the component properties (Props) used in rendering are obtained. It only needs to know how the component should be rendered with these Props. How to obtain the properties is the responsibility of the container component. When changes in the state of a presentational component need to be synchronized to the source data, a method in the container component needs to be called. This method is generally passed to the presentational component through Props.

For example, a Todo project has a Todo component and a TodoList component. The Todo component is a container component that is responsible for obtaining the to-do list from the server. After obtaining the to-do list, it is passed to the TodoList for display. . After creating a new to-do item in the TodoList, you need to call the method of saving the to-do item in the Todo component through the Props of the TodoList to synchronize the new to-do item to the server.

Container components and presentational components can be nested in each other. A container component can contain multiple presentational components and other container components; a presentational group can also contain container components and other Display component. This kind of division of labor can make the logic that is not directly related to component rendering centralized and responsible for the container component, and the presentation component only focuses on the rendering logic of the component, thus making the presentation component easier to reuse. For very simple pages, generally only one container component is enough; but for responsible pages, multiple container components are needed. Otherwise, if all business logic is processed in one container component, the component will be very complex. , at the same time, the source data obtained by this component may need to be passed through many layers of component Props before reaching the final display component used.

Props, State and the common properties of the component

The concepts of Props and State are very clear. The common properties of the component refer to the properties directly mounted under this in the component. In fact, Props and State are also two common properties of components, because we can get them directly through this.props and this.state. So in what scenarios should Props, State and other common properties of components be used?

Props and State are both used for component rendering, that is to say, what a component eventually looks like depends on the Props and State of the component. Changes in Props and State will trigger the component's render method. But there are differences between the two. Props is read-only data, which is passed from the parent component; while State is the state maintained by the component itself and is mutable. State can change based on changes in Props. If other properties are needed in the component, and this property has nothing to do with the rendering of the component (that is, it will not be used in the render method), then this property can be hung directly under this instead of being a state of the component.

For example, if you need a timer in a component and change the state of the component every few seconds, you can define a this.timer property to clear the timer when componentWillUnmount. (If you want to see more, go to the PHP Chinese website React Reference Manual column to learn)

setState Asynchronousness

React official website mentioned that this.state and this.props The update may be asynchronous, and React may merge multiple setState calls into one State update for performance reasons. So, don't rely on the values ​​of this.props and this.state to calculate the next state. Quoting a code example from the official website:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});
Copy after login

If you must do this, you can use another setState method that takes a function as a parameter. The first parameter of this function is the previous State, and the second parameter is the current one. The latest Props received. As follows:

// Correctthis.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});
Copy after login

在调用setState之后,也不能立即使用this.state获取最新状态,因为这时的state很可能还没有被更新,要想保证获取到的state是最新的state,可以在componentDidUpdate中获取this.state。也可以使用带用回调函数参数版本的setStatesetState(stateChange, [callback]),回调函数中的this.state会保证是最新的state。

componentWillReceiveProps

当组件的属性可能发生变化时,这个方法会被调用。这里说可能,是因为父组件render方法每次被调用时,子组件的这个方法都会被调用(子组件第一次初始化时除外),但并不一定每次子组件的属性都会发生变化。如果组件的State需要根据Props的变化而变化,那么这个方法就是最适合这个这个逻辑的地方。例如当Props变化时,组件的State需要重置,就可以在这个方法中调用this.setState()来重置状态。需要注意,在这个方法中调用this.setState()并不会重新触发componentWillReceiveProps的调用,也不会导致render方法被触发两次。一般情况下,接收到新Props会触发一次render,调用this.setState也会触发一次render,但在componentWillReceiveProps中调用this.setState,React会把原本需要的两次render,合并成一次。

shouldComponentUpdate

这个方法常作为优化React性能使用。当shouldComponentUpdate返回false时,组件本次的render方法不会被触发。可以通过在这个方法中比较前后两次state或者props,根据实际业务场景决定是否需要触发render方法。

React提供了一个React.PureComponent组件,这个组件重写了shouldComponentUpdate,会对前后两次的state和props进行浅比较,如何不一致,才会返回true,触发后续的render方法。这里的浅比较指,只会对state和props的第一级属性进行比较(使用!==),这满足一般的使用场景。如果你的组件继承了React.PureComponent,但在setState时,传入的state是直接修改的原有state对象,就会因为依然满足浅比较的条件,而不会重新触发render方法,导致最终DOM和state不一致。例如state={books: ['A','B']},在setState时,使用this.setState({name: this.state.books.push('C')})直接修改books对象,这样虽然books内容发生了修改,但因为对象引用并没有变化,所以依然满足浅比较条件,不会触发render方法。

一般情况下,让shouldComponentUpdate返回默认的true是不会有太大问题的。虽然这样可能导致一些不必要的render方法被调用,但render方法直接操作的是虚拟DOM,只要虚拟DOM没有发生变化,并不会导致实体DOM的修改。而JS慢是慢在实体DOM的修改上。只要你的render方法不是很复杂,多调用几次render方法并不会带来多大的性能开销。

render

父组件每次render方法被调用,或者组件自己每次调用setState方法,都会触发组件的render方法(前提是shouldComponentUpdate使用默认行为,总是返回true)。那么组件每次render,是不是都会导致实体DOM的重新创建呢?答案是,不是!

React之所以比直接操作DOM的JS库快,原因是React在实体DOM之上,抽象出一层虚拟DOM,render方法执行后,得到的是虚拟DOM,React 会把组将当前的虚拟DOM结构和前一次的虚拟DOM结构做比较,只有存在差异性,React才会把差异的内容同步到实体DOM上。如果两次render后的虚拟DOM结构保持一致,并不会触发实体DOM的修改。

React速度快的原因,还有一个是它出色的Diff算法。标准的比较两棵树的Diff算法的时间复杂是 O(n3) 。而React基于非常符合实际场景的两个假设,就将Diff算法的时间复杂度降到了接近O(n)。这两个假设是:

    <li>

    如果两个组件或元素类型不同,那么他们就是完全不同的树,不需要再比较他们的子节点。例如,<Article><Comment>将产生是两个完全的树状结构;<p>children</p><p>children</p>也是两个完全不同的树。这种情况下,组件会被完全重建,旧的DOM节点被销毁,组件经历componentWillUnmount(),然后重新创建一棵新树, 组件经历 componentWillMount()componentDidMount()

    <li>

    可以为组件或元素设置key属性,key用来标识这个组件或元素。key不需要全局唯一,只需要在兄弟组件或兄弟元素间保证唯一性就可以。key常用到集合(List)元素中。例如:

<ul><li key=&#39;a&#39;>Book A</li><li key=&#39;b&#39;>Book B</li></ul>
Copy after login

当在第一个位置插入一条记录Book C 时,

<ul><li key=&#39;c&#39;>Book C</li><li key=&#39;a&#39;>Book A</li><li key=&#39;b&#39;>Book B</li></ul>
Copy after login

由于有key的标识,React知道此时新增了一条记录,会创建一个新的<li>元素,并把它插入到列表中的第一个位置。如果没有设置key,React并不知道是新增了一条记录,还是原来的两条记录完全替换成新的三条记录,或者其他更加复杂的修改场景。React需要自上而下的比较每一条记录,这样每次比较节点都不同,所以需要修改两次节点,然后再新增一个节点,效率明显要差很多。

这里同时揭露了另一个问题,不要使用元素在集合中的索引值作为key,因为一旦集合中元素顺序发生改变,就可能导致大量的key失效,进而引起大量的修改操作。

如何发送网络请求

当我们需要从服务器获取数据时,我们应该在组件的哪一个生命周期方法中发送网络请求呢?React官网上提到,可以在componentDidMount中发送网络请求,这也是一般情况下的最佳实践。有些人也会把发送网络请求放在componentWillMount中,并且认为这个方法先于componentDidMount调用,所以可以更快地获取数据。个人认为,这种使用方法一般也是没有问题的,但在一些场景下会出现问题,比如需要在服务器端渲染时,componentWillMount会被调用两次,一次是在Server端,一次是在Client端。可参考这篇文章。

本篇文章到这就结束了(想看更多就到PHP中文网React使用手册栏目中学习),有问题的可以在下方留言提问。

The above is the detailed content of How much do you know about react? Summary of things to note about react. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build a real-time chat app with React and WebSocket How to build a real-time chat app with React and WebSocket Sep 26, 2023 pm 07:46 PM

How to build a real-time chat application using React and WebSocket Introduction: With the rapid development of the Internet, real-time communication has attracted more and more attention. Live chat apps have become an integral part of modern social and work life. This article will introduce how to build a simple real-time chat application using React and WebSocket, and provide specific code examples. 1. Technical preparation Before starting to build a real-time chat application, we need to prepare the following technologies and tools: React: one for building

Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Guide to React front-end and back-end separation: How to achieve decoupling and independent deployment of front-end and back-end Sep 28, 2023 am 10:48 AM

React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to build simple and easy-to-use web applications with React and Flask How to build simple and easy-to-use web applications with React and Flask Sep 27, 2023 am 11:09 AM

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

How to build a reliable messaging app with React and RabbitMQ How to build a reliable messaging app with React and RabbitMQ Sep 28, 2023 pm 08:24 PM

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

React responsive design guide: How to achieve adaptive front-end layout effects React responsive design guide: How to achieve adaptive front-end layout effects Sep 26, 2023 am 11:34 AM

React Responsive Design Guide: How to Achieve Adaptive Front-end Layout Effects With the popularity of mobile devices and the increasing user demand for multi-screen experiences, responsive design has become one of the important considerations in modern front-end development. React, as one of the most popular front-end frameworks at present, provides a wealth of tools and components to help developers achieve adaptive layout effects. This article will share some guidelines and tips on implementing responsive design using React, and provide specific code examples for reference. Fle using React

React Router User Guide: How to implement front-end routing control React Router User Guide: How to implement front-end routing control Sep 29, 2023 pm 05:45 PM

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

React code debugging guide: How to quickly locate and solve front-end bugs React code debugging guide: How to quickly locate and solve front-end bugs Sep 26, 2023 pm 02:25 PM

React code debugging guide: How to quickly locate and resolve front-end bugs Introduction: When developing React applications, you often encounter a variety of bugs that may crash the application or cause incorrect behavior. Therefore, mastering debugging skills is an essential ability for every React developer. This article will introduce some practical techniques for locating and solving front-end bugs, and provide specific code examples to help readers quickly locate and solve bugs in React applications. 1. Selection of debugging tools: In Re

How to build a fast data analysis application using React and Google BigQuery How to build a fast data analysis application using React and Google BigQuery Sep 26, 2023 pm 06:12 PM

How to use React and Google BigQuery to build fast data analysis applications Introduction: In today's era of information explosion, data analysis has become an indispensable link in various industries. Among them, building fast and efficient data analysis applications has become the goal pursued by many companies and individuals. This article will introduce how to use React and Google BigQuery to build a fast data analysis application, and provide detailed code examples. 1. Overview React is a tool for building

See all articles