


An introduction to three methods for distributing state across components in React
这篇文章给大家介绍的内容是关于React中跨组件分发状态的三种方法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
当我问自己第一百次时,我正在研究一个典型的CRUD屏幕:“我应该将状态保留在这个组件中还是将其移动到父组件?”。
如果需要对子组件的状态进行轻微控制。您可能也遇到了同样的问题。
让我们通过一个简单的例子和三种修复方法来回顾它。前两种方法是常见的做法,第三种方法不太常规。
问题;
为了向您展示我的意思,我将使用一个简单的书籍CRUD(译者注:增加(Create)、读取查询(Retrieve)、更新(Update)和删除(Delete))屏幕(如此简单,它没有创建和删除操作)。
我们有三个组成部分。
那么,我们的状态是什么?好吧,
import React, { Component } from "react"; import { render } from "react-dom"; const books = [ { title: "The End of Eternity", author: "Isaac Asimov" }, //... ]; const BookList = ({ books, onEdit }) => (
Book Title | Actions |
---|---|
{book.title} |
在codesandbox尝试一下
看起来不错,但是他不起作用。
我们正在创建组件实例时初始化
我们改如何修复它?
方法1:受控组件
一种常见的方法是将状态提升,将
//... class BookForm extends Component { render() { if (!this.props.book) return null; return (); } } class BookApp extends Component { state = { books: books, activeBook: null, activeIndex: -1 }; render() { const { books, activeBook, activeIndex } = this.state; return (
方法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 (); } } //...
在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会为其创建一个新实例。因此,当用户选择新书时,
相关文章推荐:
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!

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version
