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: hidden
或z-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 ref
attribute. 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, theref
created in the constructor withReact.createRef()
receives the underlying DOM element as itscurrent
property.在HTML元素上使用
ref
屬性時,在帶有React.createRef()
的構造函數中創建的ref
會接收底層的DOM元素作為其current
屬性。When the
ref
attribute is used on a custom class component, theref
object receives the mounted instance of the component as itscurrent
.在自定義類組件上使用
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 */}</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 <Transiti
on> 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.someValue
與this.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
.
它接收兩個參數nextProps
和prevState
。 正如前面提到的,你不能訪問this
這個方法里面。 您必須將道具存儲在狀態中,才能將nextProps
與以前的道具進行比較。 在上面的代碼中,將nextProps
和prevState
進行了比較。 如果兩者不同,則將返回一個對象以更新狀態。 否則,將返回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