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

Use of React: State management inside React components

不言
Release: 2018-07-20 10:40:57
Original
2096 people have browsed it

This article introduces you to the use of React: the internal state management of React components has certain reference value. Friends in need can refer to it.

In this article, we will focus on the state management within React components to understand or rethink the following three core concepts:

  1. props and state

  2. function component

  3. class component

let's start!

01. Data in React

From the perspective of "components", React divides the data flowing in the application into two types:

Props whose content cannot be changed but can be passed one-way across components;

The content can be changed, but the state cannot be passed across components;

Furthermore, the difference between props and state is that props are external and controlled by any code that renders this component. State is internal and controlled by the component itself.

Beginners who are not computer majors are often confused about the relationship between the names and meanings of props and state. In fact, you don’t need to care about them. They are essentially just another name for data, but in React, they are each given special restrictions or capabilities.

You can pass any data you want to pass to the child component through the props attribute on the component, just like passing properties in HTML. All properties will be stored in the this.props object of the child component (class component).

function Parent(props) {    
return <Child name={"Tom"} />
}function Child(props) {    
return <span>(props.name)</span>
}
Copy after login

02. Function component

We mentioned before that React uses components to render views to improve performance, and a component is a function, and its function can be expressed concisely with a formula: f (data) => UI. At this point I think you should have noticed why we say that React is not a large MVC (or MVVM) framework, because React is only responsible for the rendering of the view layer (View), and other things will be completed by other tools in the React ecosystem.

Having said that, for React components, the simplest form is the function component, which fully demonstrates the React philosophy of doing one thing at a time, componentization and data-driven UI.

Function components are also called "stateless components", "controlled components" or "puppet components" because function components are only responsible for receiving props and returning UI. It itself cannot have changeable data. In real React application development scenarios Next, we often use function components as much as possible to split the entire application UI into the smallest possible visual units.

This is because the function component is very intuitive, it receives the attribute return element, the internal logic is clear and clear, and more importantly, there is no this keyword in the function component, so you never have to worry about the annoying "this context problem".

Remember: If your component does not need to track internal state, try to use functional components.

03. Class component

Corresponding to the function component is the "class component". Similarly, it is also called "stateful component", "uncontrolled component" and "container component". It should be noted here that although we name the two types of components in the form of code, this is not rigorous, because in JavaScript, "classes" are also functions.

Unlike function components, class components have internal data that can be changed - state. It ultimately affects the rendering of the page, and state can be modified internally by the component at any time. The usual time is when the user interacts with the interface.

Because React encapsulates changing data within components and adheres to the principle of one-way data flow. We have highly abstract UI components and encapsulate complex business logic. This allows us to develop large applications by building and combining a series of small components.

So how do you add state to a class component? It's simple, all we have to do is add a state attribute inside the class component, and the state attribute is an object. This object represents the state of the component. Each attribute name of the object represents a specific state of the component. The following is the specific code:

import React from "react"class Parent extends React.Component {
    state = {
        name: "Eliot",
    }
    
    render() {        return <p>{this.state.name}</p>
    }
}
Copy after login

React 使我们迫使大脑关注两个重要的部分:

组件看起来是什么样?

组件当前的状态是什么?

通过让组件管理自己的状态,任何时候状态的变更都会令 React 自动更新相应的页面部分。这便是使用 React 构建组件的主要优势之一:当页面需要重新渲染时,我们仅仅需要思考的是如何更改状态。我们不必跟踪页面的哪些部分需要更改,不需要决定如何有效的重新呈现页面,React 自会比较先前的输出和新的输出,决定什么应该发生改变,并为我们做出决定。而这个确定之前改变了什么和现在应该新输出什么的过程有一个专门的名词,叫做 Reconciliation。

04. 修改 state

你应该还记得类组件与函数组件最大的不同在于类组件自身拥有可以改变内部数据的能力。那么如何行使这一能力呢?和直觉不同,要做到这一点,你需要使用 React 提供的专门的 API:this.setState()。

你有两种方式使用该 API:

设置对象参数;

设置函数参数;

让我们先来看看第一种:

this.setState({    name: "Tom"})
Copy after login

React 会自动合并对 state 的改变。而有时,你的组件需要一个新的 state ,而这个 state 的变化又依赖于旧的 state值,每当这种时候,你就该使用第二种 API 调用方式:

this.setState((prevState) => ({
    name: "mr." + prevState.name
}))
Copy after login

讲到这里你可能会感到奇怪,只是更新 state 而已,为什么还需要调用一个专门的 API?我们直接修改之前定义的 state对象不就好了吗?之所以这样设计的原因是,组件内 state 的变化不仅仅是对象属性值发生变化那么简单,它还需要驱动整个 UI 进行重新渲染,因此 this.setState() 这个 API 被调用时实际上做了两件事:

修改 state 对象;

驱动组件重新渲染;

如果你对 React 有一定研究,你可能会质疑我以上所罗列的两点并不精确,的确如此,小小的 this.setState() API 其实内部还有很多细节值得注意,例如,当调用 this.setState() 时并不会立即改变 state 的值,也当然不会立即重新渲染组件。例如,当以对象为参数调用 this.setState() API 时,尽管内部重复为数据赋值,最终的数据也只保留最后一次更改的结果。

不过幸好,这些略显古怪的状态早有前人为我们做了详尽的解释,如果你感兴趣,请点击下方链接查询更多的信息:

setState:这个API设计到底怎么样

问一个react更新State的问题?

05. 控制组件

当你在 Web 应用中使用表单时,这个表单的数据被存储于相应的 DOM 节点内部,但正如我们之前提到的,React 的整个关键点就在于如何高效的管理应用内的状态。所以虽然表单的数据被存储于 DOM 中,React 依然可以对它进行状态管理。

而管理的方式即是使用“控制组件”。简单而言,“控制组件”会渲染出一个表单,但是将表单所需的所有真实数据作为 state 存储于组件内部,而不是 DOM 中。

之所以被称为“控制组件”的原因也即在于此,“控制组件”控制着组件内的表单数据,因此,唯一更新表单数据的方式就是更新组件内部对应的 state 值。

import React as "react"class Input extends React.Component {
    state = {
        value: "enter something...",
    }
    
    handleClick: (e) => {        this.setState({value: e.target.value})
    }
    
    render() {
        <input value={this.state.value} onKeyup={this.handleClick} />
    }
}
Copy after login

可以看到,我们使用 handleClick 方法响应用户每一次键盘敲击以即时更新表单状态,这样做不仅天然的支持了即时的输入验证,还允许你有条件的禁止或点亮表单按钮。

06. 小结

这篇文章我们介绍了 React 的两种数据形式:state 和 props,并且介绍了 React 组件的两种形式:函数组件与类组件,希望各位有所收获。

相关推荐:

react的使用: React如何渲染UI

React的使用:react框架的五大特点

The above is the detailed content of Use of React: State management inside React components. 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!