search
HomeWeb Front-endHTML TutorialAn introduction to three methods for distributing state across components in React

这篇文章给大家介绍的内容是关于React中跨组件分发状态的三种方法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

当我问自己第一百次时,我正在研究一个典型的CRUD屏幕:“我应该将状态保留在这个组件中还是将其移动到父组件?”。

如果需要对子组件的状态进行轻微控制。您可能也遇到了同样的问题。

让我们通过一个简单的例子和三种修复方法来回顾它。前两种方法是常见的做法,第三种方法不太常规。

问题;

为了向您展示我的意思,我将使用一个简单的书籍CRUD(译者注:增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete))屏幕(如此简单,它没有创建和删除操作)。

An introduction to three methods for distributing state across components in React

我们有三个组成部分。是一个组件,显示了用于编辑它们的书籍和按钮列表。有两个输入和一个按钮,用于保存对书籍的更改。以及包含其他两个组件的

那么,我们的状态是什么?好吧,应该跟踪书籍清单以及识别当前正在编辑的书籍的内容。 没有任何状态。并且应该保持输入的当前状态,直到单击“保存”按钮。

import React, { Component } from "react";
import { render } from "react-dom";

const books = [
  {
    title: "The End of Eternity",
    author: "Isaac Asimov"
  },
  //...
];

const BookList = ({ books, onEdit }) => (
  
                            {books.map((book, index) => (                                     ))}   
Book TitleActions
{book.title}                    
); class BookForm extends Component {   state = { ...this.props.book };   render() {     if (!this.props.book) return null;     return (       
        

Book

                                 
    );   } } class BookApp extends Component {   state = {     books: books,     activeIndex: -1   };   render() {     const { books, activeIndex } = this.state;     const activeBook = books[activeIndex];     return (       
                     this.setState({               activeIndex: index             })}         />                      this.setState({               books: Object.assign([...books], { [activeIndex]: book }),               activeIndex: -1             })}         />       
    );   } } render(, document.getElementById("root"));

在codesandbox尝试一下

看起来不错,但是他不起作用。

我们正在创建组件实例时初始化状态,因此,当从列表中选择另一本书时,父级无法让它知道它需要更改它。

我们改如何修复它?

方法1:受控组件

一种常见的方法是将状态提升,将转换为受控组件。我们删除状态,将activeBook添加到状态,并向添加一个onChange道具,我们在每次输入时都会调用它。

//...

class BookForm extends Component {
  render() {
    if (!this.props.book) return null;
    return (
      
        

Book

                                 
    );   } } class BookApp extends Component {   state = {     books: books,     activeBook: null,     activeIndex: -1   };   render() {     const { books, activeBook, activeIndex } = this.state;     return (       
                     this.setState({               activeBook: { ...books[index] },               activeIndex: index             })}         />          this.setState({ activeBook: book })}           onSave={() =>             this.setState({               books: Object.assign([...books], { [activeIndex]: activeBook }),               activeBook: null,               activeIndex: -1             })}         />       
    );   } } //...

方法2:同步state

现在它可以工作,但对我来说,提升的状态感觉不对。在用户单击“保存”之前,不关心对书的任何更改,那么为什么需要将其保持在自己的状态?

在codesandbox尝试一下

现在它可以工作,但对我来说,提升的状态感觉不对。在用户单击“保存”之前,不关心对书的任何更改,那么为什么需要将其保持在自己的状态?

//...
class BookForm extends Component {
  state = { ...this.props.book };
  componentWillReceiveProps(nextProps) {
    const nextBook = nextProps.book;
    if (this.props.book !== nextBook) {
      this.setState({ ...nextBook });
    }
  }
  render() {
    if (!this.props.book) return null;
    return (
      
        

Book

                                 
    );   } } //...

在codesandbox尝试一下

这种方法通常被认为是一种不好的做法,因为它违背了React关于拥有单一事实来源的想法。我不确定是这种情况,然而,同步状态并不总是那么容易。此外,我尽量避免使用生命周期方法。

方法3:由Key控制的组件

但为什么我们要回收旧的状态呢?每次用户选择一本书时,拥有一个全新状态的新实例是不是有意义?

为此,我们需要告诉React停止使用旧实例并创建一个新实例。这就是key prop的用途。

//...
class BookApp extends Component {
  state = {
books: books,
activeIndex: -1
};
  render() {
const { books, activeIndex } = this.state;
const activeBook = books[activeIndex];
return (
  <div>
    <booklist>
        this.setState({
          activeIndex: index
        })}
    />
    <bookform>
        this.setState({
          books: Object.assign([...books], { [activeIndex]: book }),
          activeIndex: -1
        })}
    />
  </bookform></booklist>
</div>
);
}
}
//...

在codesandbox尝试一下。

如果元素具有与上一个渲染不同的键,则React会为其创建一个新实例。因此,当用户选择新书时,的键更改,将创建组件的新实例,并从props初始化状态。

相关文章推荐:

React Native跨域资源加载出错如何解决

React-JSX中如何实现Class与Style的动态绑定(附实例)

The above is the detailed content of An introduction to three methods for distributing state across components in React. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor