react和react2_為什么React16是React開發人員的福氣

react和react2

by Harsh Makadia

通過苛刻馬卡迪亞

為什么React16是React開發人員的福氣 (Why React16 is a blessing to React developers)

Just like how people are excited about updating their mobile apps and OS, developers should also be excited to update their frameworks. The new version of the different frameworks come with new features and tricks out of the box.

就像人們對更新其移動應用程序和操作系統感到興奮一樣,開發人員也應該對更新其框架感到興奮。 不同框架的新版本具有開箱即用的新功能和技巧。

Below are some of the good features you should consider when migrating your existing app to React 16 from React 15.

以下是將現有應用程序從React 15遷移到React 16時應考慮的一些良好功能。

Time to say Goodbye React15 ?

是時候說再見React15了?

錯誤處理 (Error Handling)

React 16 introduces the new concept of an error boundary.

React 16引入了錯誤邊界的新概念。

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree. They log those errors, and display a fallback UI instead of the crashed component tree. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

錯誤邊界是React組件,可在其子組件樹的任何位置捕獲JavaScript錯誤。 他們記錄這些錯誤,并顯示后備UI而不是崩潰的組件樹。 錯誤邊界會在渲染期間,生命周期方法以及它們下面的整個樹的構造函數中捕獲錯誤。

A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info):

如果類組件定義了一個稱為componentDidCatch(error, info)新生命周期方法,則它將成為錯誤邊界:

Then you can use it as a regular component.

然后,您可以將其用作常規組件。

<ErrorBoundary>     <MyWidget /></ErrorBoundary>

The componentDidCatch() method works like a JavaScript catch {} block, but for components. Only class components can be error boundaries. In practice, most of the time you’ll want to declare an error boundary component once. Then you’ll use it throughout your application.

componentDidCatch()方法的工作方式類似于JavaScript catch {}塊,但適用于組件。 只有類組件才能成為錯誤邊界。 實際上,大多數情況下,您只需要聲明一次錯誤邊界組件。 然后,您將在整個應用程序中使用它。

Note that error boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself. If an error boundary fails trying to render the error message, the error will propagate to the closest error boundary above it. This, too, is similar to how catch {} block works in JavaScript.

請注意, 錯誤邊界僅捕獲樹中位于其下方的組件中的錯誤 。 錯誤邊界本身無法捕獲錯誤。 如果錯誤邊界在嘗試呈現錯誤消息時失敗,則錯誤將傳播到其上方最近的錯誤邊界。 這也類似于catch {}塊在JavaScript中的工作方式。

Check out the live demo:

查看現場演示:

For more information on error handling, head here.

有關錯誤處理的更多信息,請訪問此處 。

新的渲染返回類型:片段和字符串 (New render return types: fragments and strings)

Get rid of wrapping the component in a div while rendering.

消除在渲染時將組件包裝在div中的麻煩。

You can now return an array of elements from a component’s render method. Like with other arrays, you’ll need to add a key to each element to avoid the key warning:

現在,您可以從組件的render方法返回一個元素數組。 與其他數組一樣,您需要向每個元素添加一個鍵,以避免出現鍵警告:

render() {  // No need to wrap list items in an extra element!  return [    // Don't forget the keys :)    <li key="A">First item</li>,    <li key="B">Second item</li>,    <li key="C">Third item</li>,  ];}

Starting with React 16.2.0, it has support for a special fragment syntax to JSX that doesn’t require keys.

從React 16.2.0開始 ,它支持JSX不需要密鑰的特殊片段語法。

Support for returning strings :

支持返回字符串:

render() {  return 'Look ma, no spans!';}

門戶網站 (Portals)

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

門戶網站提供了一種一流的方法來將子級呈現到父組件的DOM層次結構之外的DOM節點中。

ReactDOM.createPortal(child, container)

The first argument (child) is any renderable React child, such as an element, string, or fragment. The second argument (container) is a DOM element.

第一個參數( child )是任何可渲染的React child ,例如元素,字符串或片段。 第二個參數( container )是DOM元素。

如何使用它 (How to use it)

When you return an element from a component’s render method, it’s mounted into the DOM as a child of the nearest parent node:

當您從組件的render方法返回一個元素時,該元素將作為最近的父節點的子節點安裝到DOM中:

render() {  // React mounts a new div and renders the children into it  return (    <div>      {this.props.children}    </div>  );}

Sometimes it’s useful to insert a child into a different location in the DOM:

有時將子級插入DOM中的其他位置很有用:

render() {  // React does *not* create a new div. It renders the children into `domNode`.  // `domNode` is any valid DOM node, regardless of its location in the DOM.  return ReactDOM.createPortal(    this.props.children,    domNode  );}

A typical use case for portals is when a parent component has an overflow: hidden or z-index style, but you need the child to visually “break out” of its container. For example, dialogs, hovercards, and tooltips.

門戶的典型用例是父組件出現overflow: hiddenz-index樣式,但是您需要子組件以可視方式“脫離”其容器。 例如,對話框,懸浮卡和工具提示。

自定義DOM屬性 (Custom DOM Attribute)

React15 used to ignore any unknown DOM attributes. It would just skip them since React didn’t recognize it.

React15用來忽略任何未知的DOM屬性。 由于React無法識別,因此只會跳過它們。

// Your code:<div mycustomattribute="something" />

Would render an empty div to the DOM with React 15:

使用React 15將一個空的div呈現給DOM:

// React 15 output:<div />

In React16, the output will be the following (custom attributes will be shown and not be ignored at all):

在React16中,輸出將如下所示( 將顯示自定義屬性,而根本不會忽略它 ):

// React 16 output:<div mycustomattribute="something" />

避免在狀態為NULL的情況下重新渲染 (Avoid Re-render with setting NULL in state)

With React16 you can prevent state updates and re-renders right from setState(). You just need to have your function return null.

使用React16,您可以阻止狀態更新并直接從setState()重新渲染。 您只需要讓函數返回null

const MAX_PIZZAS = 20;function addAnotherPizza(state, props) {  // Stop updates and re-renders if I've had enough pizzas.  if (state.pizza === MAX_PIZZAS) {    return null;  }  // If not, keep the pizzas coming! :D  return {    pizza: state.pizza + 1,  }}this.setState(addAnotherPizza);

Read more here.

在這里。

創建參考 (Creating Refs)

Creating refs with React16 is now much easier. Why you need to use refs:

現在,使用React16創建引用變得容易得多。 為什么需要使用裁判:

  • Managing focus, text selection, or media playback.

    管理焦點,文本選擇或媒體播放。
  • Triggering imperative animations.

    觸發命令式動畫。
  • Integrating with third-party DOM libraries.

    與第三方DOM庫集成。

Refs are created using React.createRef() and are attached to React elements via the refattribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

使用React.createRef()創建React.createRef()并通過ref屬性將其附加到React元素。 構造組件時,通常將引用分配給實例屬性,以便可以在整個組件中對其進行引用。

class MyComponent extends React.Component {  constructor(props) {    super(props);    this.myRef = React.createRef();  }  render() {    return <div ref={this.myRef} />;  }}

訪問參考 (Accessing Refs)

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

將ref傳遞到render的元素時,可以在ref的current屬性處訪問對節點的引用。

const node = this.myRef.current;

The value of the ref differs depending on the type of the node:

ref的值根據節點的類型而有所不同:

  • When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.

    在HTML元素上使用ref屬性時,在帶有React.createRef()的構造函數中創建的ref會接收底層的DOM元素作為其current屬性。

  • When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.

    在自定義類組件上使用ref屬性時, ref對象將接收該組件的已安裝實例作為其current

  • You may not use the ref attribute on functional components because they don’t have instances.

    您不能在功能組件上使用ref屬性,因為它們沒有實例。

上下文API (Context API)

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

上下文提供了一種通過組件樹傳遞數據的方法,而不必在每個級別手動傳遞道具。

React.createContext (React.createContext)

const {Provider, Consumer} = React.createContext(defaultValue);

Creates a { Provider, Consumer } pair. When React renders a context Consumer, it will read the current context value from the closest matching Provider above it in the tree.

創建一個{ Provider, Consumer }對。 當React渲染一個上下文Consumer ,它將從樹中它上面最接近的匹配Provider讀取當前上下文值。

The defaultValue argument is only used by a Consumer when it does not have a matching Provider above it in the tree. This can be helpful for testing components in isolation without wrapping them. Note: passing undefined as a Provider value does not cause Consumers to use defaultValue.

當使用者在樹中上方沒有匹配的提供者時, 使用defaultValue參數。 這對于隔離測試組件而不包裝它們很有幫助。 注意:將undefined傳遞為Provider值不會導致使用者使用defaultValue

Provider (Provider)

<Provider value={/* some value */}>

A React component that allows Consumers to subscribe to context changes.

一個React組件,它允許使用者訂閱上下文更改。

Accepts a value prop to be passed to Consumers that are descendants of this Provider. One Provider can be connected to many Consumers. Providers can be nested to override values deeper within the tree.

接受要傳遞給作為此提供者后代的消費者的value支持。 一個提供商可以連接到許多消費者。 可以嵌套提供程序以覆蓋樹中更深的值。

Consumer (Consumer)

<Consumer>  {value => /* render something based on the context value */}&lt;/Consumer>

A React component that subscribes to context changes.

訂閱上下文更改的React組件。

Requires a function as a child. The function receives the current context value and returns a React node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the value argument will be equal to the defaultValue that was passed to createContext().

需要一個孩子的功能 。 該函數接收當前上下文值并返回一個React節點。 傳遞給函數的value參數將等于樹中以上上下文的最接近Provider的value prop。 如果上面的上下文沒有提供者,則value參數將等于傳遞給createContext()defaultValue

static getDerivedStateFromProps() (static getDerivedStateFromProps())

getDerivedStateFromProps is invoked right before calling the render method. Both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

在調用render方法之前,將getDerivedStateFromProps調用getDerivedStateFromProps 。 無論是在初始安裝還是在后續更新中。 它應該返回一個對象以更新狀態,或者返回null則不更新任何內容。

This method exists for rare use cases where the state depends on changes in props over time. For example, it might be handy for implementing a <Transition> component that compares its previous and next children to decide which of them to animate in and out.

此方法適用于狀態依賴于道具隨時間變化的罕見用例 。 例如,實現一個<Transiti on>組件比較上一個和下一個子對象,以確定要對其中的哪個子對象進行動畫制作,可能會很方便。

Deriving state leads to verbose code and makes your components difficult to think about.

派生狀態會導致冗長的代碼,并使您的組件難以考慮。

Make sure you’re familiar with simpler alternatives:

確保您熟悉更簡單的替代方法:

  • If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

    如果您需要根據道具的變化執行副作用 (例如,數據獲取或動畫),請改用componentDidUpdate生命周期。

  • If you want to re-compute some data only when a prop changes, use a memoization helper instead.

    如果僅在更改道具時才重新計算某些數據 ,請改用備忘錄助手 。

  • If you want to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled with a key instead.

    如果你想“復位”一些狀態,當道具的變化 ,無論是考慮使組件完全控制或完全不受控制一key代替。

This method doesn’t have access to the component instance. If you’d like, you can reuse some code between getDerivedStateFromProps() and the other class methods by extracting pure functions of the component props and state outside the class definition.

此方法無權訪問組件實例。 如果愿意,可以通過在類定義之外提取組件props和state的純函數來在getDerivedStateFromProps()和其他類方法之間重用一些代碼。

Note that this method is fired on every render, regardless of the cause. This is in contrast to UNSAFE_componentWillReceiveProps. It only fires when the parent causes a re-render and not as a result of a local setState.

請注意,無論原因如何,都會在每個渲染器上觸發此方法。 這與UNSAFE_componentWillReceiveProps相反。 僅在父級導致重新渲染而不是由于本地setState導致時才觸發。

We compare nextProps.someValue with this.props.someValue. If both are different then we perform some operation, setState

我們將nextProps.someValuethis.props.someValue.進行比較this.props.someValue. 如果兩者不同,則我們執行一些操作setState

static getDerivedStateFromProps(nextProps, prevState){   if(nextProps.someValue!==prevState.someValue){        return { someState: nextProps.someValue};  } else return null;}

It receives two params nextProps and prevState. As mentioned previously, you cannot access this inside this method. You’ll have to store the props in the state to compare the nextProps with previous props. In above code nextProps and prevState are compared. If both are different then an object will be returned to update the state. Otherwise null will be returned indicating state update not required. If state changes then componentDidUpdate is called where we can perform the desired operations as we did in componentWillReceiveProps.

它接收兩個參數nextPropsprevState 。 正如前面提到的,你不能訪問this這個方法里面。 您必須將道具存儲在狀態中,才能將nextProps與以前的道具進行比較。 在上面的代碼中,將nextPropsprevState進行了比較。 如果兩者不同,則將返回一個對象以更新狀態。 否則,將返回null指示不需要更新狀態。 如果狀態發生變化,則將調用componentDidUpdate ,在其中我們可以像在componentWillReceiveProps一樣執行所需的操作。

獎勵:React Lifecycle事件 (Bonus: React Lifecycle events)

Lifecycle credits — https://twitter.com/dceddia

生命周期積分-https: //twitter.com/dceddia

Well these are some of the features that you should definitely try while working with React16!

好了,這些是您在使用React16時一定要嘗試的一些功能!

Happy coding ? ?

編碼愉快嗎? ?

翻譯自: https://www.freecodecamp.org/news/why-react16-is-a-blessing-to-react-developers-31433bfc210a/

react和react2

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393438.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393438.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393438.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

jzoj4598. 【NOIP2016模擬7.9】準備食物

一個th的題&#xff08;a gensokyo&#xff09; 難度系數在該知識點下為$2.1$ 區間xor我們很明顯會想到trie樹&#xff0c;將每一個區間$l~r$異或和拆成$sum[l-1]$ $sum[r]$兩個數的異或 注意到二進制的性質&#xff0c;比當前低的位即使都取1加起來都沒有這位選1答案高&#x…

java number轉string_Java Number類, Character類,String類

字符串在Java編程中廣泛使用&#xff0c;字符串就是一系列字符(由一個個的字符組成)。 在Java編程語言中&#xff0c;字符串被視為對象。Java平臺提供String類來創建和操作字符串。1. 創建字符串創建字符串的最直接方法是 -String str "Hello world!";每當它在代碼中…

Android商城開發系列(二)——App啟動歡迎頁面制作

商城APP一般都會在應用啟動時有一個歡迎界面&#xff0c;下面我們來實現一個最簡單的歡迎頁開發&#xff1a;就是打開商城App&#xff0c;先出現歡迎界面&#xff0c;停留幾秒鐘&#xff0c;自動進入應用程序的主界面。 首先先定義WelcomeActivity布局&#xff0c;布局非常簡單…

DELL安裝不了mysql_Windows 版本 Mysql 8.x 安裝

1、官網下載安裝包百度網盤鏈接&#xff1a;https://pan.baidu.com/s/1cFRbQM5720xrzMxbgjPeyA提取碼&#xff1a;xlz72、解壓安裝包并新建一個文件夾作為安裝目錄(mysqlInstall)3、配置 Mysql 環境變量4、在解壓好的目錄下新建一個 my.ini 文件(注意&#xff1a;my.ini 文件和…

lambda 使用_如何使用Lambda和API網關構建API

lambda 使用Do you want to access your database, control your system, or execute some code from another website? An API can do all of this for you, and they’re surprisingly easy to set up.您是否要訪問數據庫&#xff0c;控制系統或從其他網站執行一些代碼&…

Hyper-V Server聯機調整虛擬硬盤大小

1. 技術概述&#xff1a; 從 Windows Server 2012 R2開始&#xff0c;管理員可以在運行虛擬機的同時&#xff0c;使用 Hyper-V 來擴展或壓縮虛擬硬盤的大小。存儲管理員可以通過對運行中的虛擬硬盤執行維護操作來避免代價不菲的停機。不再需要關閉虛擬機&#xff0c;這可以避免…

leetcode162. 尋找峰值(二分法)

峰值元素是指其值大于左右相鄰值的元素。 給定一個輸入數組 nums&#xff0c;其中 nums[i] ≠ nums[i1]&#xff0c;找到峰值元素并返回其索引。 數組可能包含多個峰值&#xff0c;在這種情況下&#xff0c;返回任何一個峰值所在位置即可。 你可以假設 nums[-1] nums[n] -…

python網絡爬蟲(5)BeautifulSoup的使用示范

創建并顯示原始內容 其中的lxml第三方解釋器加快解析速度 import bs4 from bs4 import BeautifulSoup html_str """ <html><head><title>The Dormouses story</title></head> <body> <p class"title"><…

Mingw編譯DLib

Mingw編譯DLib 因為機器上安裝了qt-opensource-windows-x86-mingw530-5.8.0&#xff0c;所以準備使用其自帶的mingw530來編譯DLib使用。 因為DLib使用CMake的構建腳本&#xff0c;所以還請先安裝好CMake。 cmake的下載地址如下https://cmake.org/files/v3.7/cmake-3.7.2-win64-…

探索JavaScript的關閉功能

Discover Functional JavaScript was named one of the best new Functional Programming books by BookAuthority!“發現功能JavaScript”被BookAuthority評為最佳新功能編程書籍之一 &#xff01; A closure is an inner function that has access to the outer scope, even…

QueryList 配置curl參數 的文檔位置 QueryList抓取https 終于找到了

需要設置ssl證書&#xff0c;或者不驗證證書&#xff0c;例&#xff1a;$ql QueryList::get(https://...,[],[verify > false]);設置這個 verify > false , 所以curl的其他參數就在這里配置即可 文檔在 https://guzzle-cn.readthedocs.io/zh_CN/latest/request-optio…

leetcode981. 基于時間的鍵值存儲(treemap)

創建一個基于時間的鍵值存儲類 TimeMap&#xff0c;它支持下面兩個操作&#xff1a; set(string key, string value, int timestamp) 存儲鍵 key、值 value&#xff0c;以及給定的時間戳 timestamp。 2. get(string key, int timestamp) 返回先前調用 set(key, value, times…

物聯網筆記

轉載于:https://www.cnblogs.com/16-C-kai/p/6596682.html

關于大學生玩網絡游戲的調查問卷

1.創建問卷&#xff0c;輸入調查名稱 2編輯問卷 3檢查問卷&#xff0c;是否有誤 4.提交并發布問卷 5分享問卷 6.問卷分析 轉載于:https://www.cnblogs.com/dzw1996/p/7786754.html

java自動排序_java ArrayList自動排序算法的實現

前幾天寫的那個是錯誤的&#xff0c;在這里將正確的更新。。。通過實現ComParator接口&#xff0c;并且對Compare函數進行重寫&#xff0c;自定義排序規則實現對ArrayList中對象的排序。。Student類定義&#xff1a;通過右鍵-》source-》自動生成Set和get方法package first;imp…

1到100的二進制編碼_每天經過100天的編碼后,我學到了什么

1到100的二進制編碼Eleftheria Batsou is a web developer from Thessaloniki, Greece. She gave a talk at the Codegarden conference about her experience doing a solid 100 days of coding every day as part of the #100DaysOfCode Challenge.Eleftheria Batsou是來自希…

第六次 實驗

轉載于:https://www.cnblogs.com/P201821440005/p/10967987.html

leetcode658. 找到 K 個最接近的元素(二分法)

給定一個排序好的數組&#xff0c;兩個整數 k 和 x&#xff0c;從數組中找到最靠近 x&#xff08;兩數之差最小&#xff09;的 k 個數。返回的結果必須要是按升序排好的。如果有兩個數與 x 的差值一樣&#xff0c;優先選擇數值較小的那個數。 示例 1: 輸入: [1,2,3,4,5], k4,…

du命令、df命令用法

一、du命令 [plain] view plaincopy print?[rootwc1 mysql]# du --help Usage: du [OPTION]... [FILE]... or: du [OPTION]... --files0-fromF Summarize disk usage of each FILE, recursively for directories. Mandatory arguments to long options are mandatory…

mysql 循環創建列_mysql – 查詢列中的循環值

我需要創建一個查詢,一次只將一列的值移動一行↑&#xff1a;----------------------------| anotherCOL | values_to_loop |----------------------------| 1 | 1 || 2 | 2 || 3 | 3 || 4 | 4 || 5 | 5 || 6 | 6 || 7 | 7 || 8 | 8 || 9 | 9 || 10 | 10 |--------------------…