Home > Web Front-end > JS Tutorial > body text

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

寻∝梦
Release: 2018-09-11 11:23:05
Original
1419 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!