亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專(zhuān)欄INFORMATION COLUMN

【譯】State and Lifecycle (State和生命周期)

dadong / 1770人閱讀

摘要:結(jié)果如下打開(kāi)試試下一步,我們將把組件功能自己設(shè)置定時(shí)器并且能每秒更新。這是一個(gè)設(shè)置定時(shí)器的好地方注意我們是怎么保存定時(shí)器的。我們將在這個(gè)生命周期的函數(shù)方法中卸載掉定時(shí)器最后,我們會(huì)每一秒跑方法。

下面是react官方文檔的個(gè)人翻譯,如有翻譯錯(cuò)誤,請(qǐng)多多指出
原文地址:https://facebook.github.io/re...

Consider the ticking clock example from one of the previous sections.
思考一下,我們之前提到過(guò)的時(shí)鐘例子。
So far we have only learned one way to update the UI.
到目前為止,我們只學(xué)到一種更新UI的方式。
We call ReactDOM.render() to change the rendered output:
我們調(diào)用ReactDOM.render()的方法來(lái)改變渲染的輸出:

function tick() {
  const element = (
    

Hello, world!

It is {new Date().toLocaleTimeString()}.

); ReactDOM.render( element, document.getElementById("root") ); } setInterval(tick, 1000);

打開(kāi)試試

In this section, we will learn how to make the Clock component truly reusable and encapsulated.
在這一章,我們會(huì)學(xué)到怎么把Clock組件變得真正的可重用以及封裝。
It will set up its own timer and update itself every second.
這會(huì)讓配置我們的timer組件并且每秒自我更新。

We can start by encapsulating how the clock looks:
我們從怎么封裝Clock開(kāi)始:

function Clock(props) {
  return (
    

Hello, world!

It is {props.date.toLocaleTimeString()}.

); } function tick() { ReactDOM.render( , document.getElementById("root") ); } setInterval(tick, 1000);

打開(kāi)試試

However, it misses a crucial requirement: the fact that the Clock sets up a timer and updates the UI every second should be an implementation detail of the Clock.
然而,這會(huì)錯(cuò)過(guò)一個(gè)至關(guān)重要的需求: Clock設(shè)置一個(gè)計(jì)時(shí)器并且每秒鐘更新UI是一個(gè)時(shí)鐘的實(shí)現(xiàn)細(xì)節(jié)。

Ideally we want to write this once and have the Clock update itself:
理想狀況下,我們先寫(xiě)一次然后這個(gè)Clock能自我更新:

ReactDOM.render(
  ,
  document.getElementById("root")
);

To implement this, we need to add "state" to the Clock component.
要實(shí)現(xiàn)這一點(diǎn),我們需要添加“state” 到 Clock組件。

State is similar to props, but it is private and fully controlled by the component.
stateporps很相似,但是這是組件私有的并且是受組件控制的。

We mentioned before that components defined as classes have some additional features.
我們?cè)谇懊嫣峒斑^(guò),用類(lèi)的形式定義組件有一些額外的功能。

Local state is exactly that: a feature available only to classes.
本地state就是:只有一個(gè)特征類(lèi)。

Converting a Function to a Class

將一個(gè)函數(shù)轉(zhuǎn)換為一個(gè)類(lèi)

You can convert a functional component like Clock to a class in five steps:
你能通過(guò)五步把一個(gè)函數(shù)組件轉(zhuǎn)化為類(lèi)組件

Create an ES6 class with the same name that extends React.Component. 創(chuàng)建一個(gè)同名的類(lèi)組件并且繼承React.Compoent

Add a single empty method to it called render().添加一個(gè)空的方法叫做render()

Move the body of the function into the render() method.把函數(shù)里面的內(nèi)容移到render方法里面。

Replace props with this.props in the render() body.把render()里面的props替換成this.props

Delete the remaining empty function declaration.刪掉之前的函數(shù)聲明的組件。

class Clock extends React.Component {
  render() {
    return (
      

Hello, world!

It is {this.props.date.toLocaleTimeString()}.

); } }

打開(kāi)試試

Clock is now defined as a class rather than a function.
Clock現(xiàn)在定義成一個(gè)類(lèi)組件比定義成函數(shù)組件好。

This lets us use additional features such as local state and lifecycle hooks.
因?yàn)檫@讓我們添加一些新的功能例如本地state以及生命周期。

Adding Local State to a Class

添加State

We will move the date from props to state in three steps:
我們將用三步把props移到state

1) Replace this.props.date with this.state.date in the render() method:
render()方法里的this.props.date替換成 this.state.date

class Clock extends React.Component {
  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } }

2) Add a class constructor that assigns the initial this.state:
添加class constructor 用來(lái)初始化this.state

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } }

Note how we pass props to the base constructor:
注意,我們是怎么把props傳遞到constructor的:

 constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

Class components should always call the base constructor with props.
類(lèi)組件應(yīng)該調(diào)用constructor時(shí)候帶著props

3) Remove the date prop from the element:
中的 date props移除掉:

ReactDOM.render(
  ,
  document.getElementById("root")
);

We will later add the timer code back to the component itself.
我們將會(huì)添加回定時(shí)器代碼到組件本身。
The result looks like this:
結(jié)果如下:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } } ReactDOM.render( , document.getElementById("root") );

打開(kāi)試試
Next, we"ll make the Clock set up its own timer and update itself every second.
下一步,我們將把組件功能自己設(shè)置定時(shí)器并且能每秒更新。

Adding Lifecycle Methods to a Class

添加周期方法到類(lèi)組件

In applications with many components, it"s very important to free up resources taken by the components when they are destroyed.
在有許多組件的應(yīng)用里, 當(dāng)組件被銷(xiāo)毀的時(shí)候釋放掉資源是非常重要的。

We want to set up a timer whenever the Clock is rendered to the DOM for the first time.
我們想讓Clock組件在第一次渲染在DOM的時(shí)候設(shè)置定時(shí)器。

This is called "mounting" in React.
我們?cè)赗eact中稱(chēng)為"mounting"。

We also want to clear that timer whenever the DOM produced by the Clock is removed.
我們同樣當(dāng)組件被移除的手請(qǐng)

This is called "unmounting" in React.
我們?cè)赗eact中稱(chēng)為"unmounting"。

We can declare special methods on the component class to run some code when a component mounts and unmounts:
我們?cè)陬?lèi)組件里生命一些特別的方法當(dāng)組件mountsunmounts的時(shí)候去運(yùn)行一些代碼:


class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {

  }

  componentWillUnmount() {

  }

  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } }

These methods are called "lifecycle hooks".
這些方法被稱(chēng)為“生命周期方法鉤子"。

The componentDidMount() hook runs after the component output has been rendered to the DOM. This is a good place to set up a timer:
這個(gè)componentDidMount的方法會(huì)在組件渲染在dom上后被調(diào)用。這是一個(gè)設(shè)置定時(shí)器的好地方:

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

Note how we save the timer ID right on this.
注意我們是怎么保存定時(shí)器ID的。

While this.props is set up by React itself and this.state has a special meaning, you are free to add additional fields to the class manually if you need to store something that is not used for the visual output.
當(dāng)this.props被初始化在React,而且 this.state有一個(gè)特殊的意義,你可以手動(dòng)地自由地添加額外的字段到類(lèi)中,如果你需要存儲(chǔ)一些你不被用來(lái)輸出渲染

If you don"t use something in render(), it shouldn"t be in the state.
如果你不使用render()方法,就不應(yīng)該用在state里。

We will tear down the timer in the componentWillUnmount() lifecycle hook:
我們將在componentWillUnmount這個(gè)生命周期的函數(shù)方法中卸載掉定時(shí)器:

componentWillUnmount() {
    clearInterval(this.timerID);
  }

Finally, we will implement the tick() method that runs every second.
最后,我們會(huì)每一秒跑tick()方法。

It will use this.setState() to schedule updates to the component local state:
我們會(huì)用this.setState()來(lái)安排組件本地的state更新:

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      

Hello, world!

It is {this.state.date.toLocaleTimeString()}.

); } } ReactDOM.render( , document.getElementById("root") );

打開(kāi)試試

Now the clock ticks every second.
現(xiàn)在,時(shí)鐘每一秒都在轉(zhuǎn)動(dòng)。

Let"s quickly recap what"s going on and the order in which the methods are called:
讓我們快速回顧一下,發(fā)生了什么并且我們是怎么去調(diào)用這些方法的。

1) When is passed to ReactDOM.render(), React calls the constructor of the Clock component.
當(dāng)作為參數(shù)傳遞ReactDOM.render()的時(shí)候,React調(diào)用Clock組件中的constructor函數(shù)。
Since Clock needs to display the current time, it initializes this.state with an object including the current time.
由于Clock需要顯示正確的時(shí)間,因此我們初始化this.state成一個(gè)object包含這正確的時(shí)間。
We will later update this state.
我們稍后會(huì)更新這個(gè)state。
2) React then calls the Clock component"s render() method. This is how React learns what should be displayed on the screen.
React 稍后會(huì)調(diào)用Clock組件的render()方法。這就是React怎樣知道什么東西應(yīng)該渲染到界面上。
React then updates the DOM to match the Clock"s render output.
React 稍后會(huì)更新DOM來(lái)保證Clock正確的渲染輸出
3) When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle hook.
當(dāng)Clock輸出被插入到DOM里面,React會(huì)調(diào)用componentDidMount()的方法。
Inside it, the Clock component asks the browser to set up a timer to call tick() once a second.
之后,Clock組件會(huì)在瀏覽器里設(shè)置定時(shí)器并且開(kāi)始tick()方法。

4) Every second the browser calls the tick() method.
每一秒瀏覽器調(diào)用tick方法。
Inside it, the Clock component schedules a UI update by calling setState() with an object containing the current time.
在里面,Clock組件會(huì)安排一個(gè)UI通過(guò)調(diào)用setState()并且傳入一個(gè)時(shí)間的對(duì)象來(lái)更新。
Thanks to the setState() call, React knows the state has changed, and calls render() method again to learn what should be on the screen.
由于setState()調(diào)用,React知道state的改變,并且再次調(diào)用render()方法來(lái)讓界面知道怎么改變。
This time, this.state.date in the render() method will be different, and so the render output will include the updated time.
這一次,this.state.datarender()方法將會(huì)不一樣,所以渲染接輸出講包括更新時(shí)間。
React updates the DOM accordingly.
React相應(yīng)地更新DOM。

5) If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle hook so the timer is stopped.
如果Clock組件要從DOM外移除,React會(huì)調(diào)用componentWillUnmount()函數(shù),并且是定時(shí)器停止。

Using State Correctly

正確使用State

There are three things you should know about setState().
有三件關(guān)于的setState的事你必須知道

Do Not Modify State Directly

別直接修改State的值

For example, this will not re-render a component:
例如,這不會(huì)重新渲染一個(gè)組件:

// Wrong
this.state.comment = "Hello";

Instead, use setState():
我們要用setState()來(lái)代替:

// Correct
this.setState({comment: "Hello"});

The only place where you can assign this.state is the constructor.
你唯一能聲明this.state的地方只有在constructor里

State Updates May Be Asynchronous

State的更新有可能是異步的

React may batch multiple setState() calls into a single update for performance.
React 為了性能,可能會(huì)把批量處理多次的setState() 調(diào)用在一個(gè)的更新里。

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
因?yàn)?b>this.props和this.state可能異步更新了,你不應(yīng)該依賴(lài)他們的值來(lái)計(jì)算下一個(gè)state。

For example, this code may fail to update the counter:
例如, 下面的代碼可能會(huì)更新計(jì)算器失敗:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object.
為了解決這個(gè)問(wèn)題,讓setState()接收一個(gè)函數(shù)比接收一個(gè)對(duì)象的方式更好。
That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:
這個(gè)函數(shù)會(huì)把前一個(gè)state作為第一個(gè)參數(shù), 并且props在那時(shí)更新并被作為第二參數(shù):

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

We used an arrow function above, but it also works with regular functions:
我們?cè)谏厦娴暮瘮?shù)用了箭頭函數(shù),我們使用常規(guī)的函數(shù)也一樣可用:

// Correct
this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});
State Updates are Merged

state的更新是合并后的

When you call setState(), React merges the object you provide into the current state.
當(dāng)你調(diào)用setState(),React會(huì)合并你提供的對(duì)象到當(dāng)前的state里。

For example, your state may contain several independent variables:
例如:你的state可能包含幾個(gè)獨(dú)立的變量:

constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }

Then you can update them independently with separate setState() calls:
然后你就能獨(dú)立更新他們通過(guò)多帶帶調(diào)用setState()

componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });

    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
  }

The merging is shallow, so this.setState({comments}) leaves this.state.posts intact, but completely replaces this.state.comments.
這個(gè)合并是淺合并,所以this.setState({comments})會(huì)讓this.state.posts完整,但是會(huì)完全替換掉this.state.comments.

The Data Flows Down

單向數(shù)據(jù)流

Neither parent nor child components can know if a certain component is stateful or stateless, and they shouldn"t care whether it is defined as a function or a class.

所有的父組件或者子組件都不知道一個(gè)組件是stateful或者stateless的,并且他們也不應(yīng)該關(guān)心自己是被定義成一個(gè)函數(shù)或者是類(lèi)組件。

This is why state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it.
這就是為什么state經(jīng)常被本地調(diào)用或者被封裝。對(duì)于別的組件來(lái)說(shuō),組件的擁有的state是不可被訪問(wèn)的。

A component may choose to pass its state down as props to its child components:
一個(gè)組件可能會(huì)把自己的state作為props傳遞給他們的子組件中:

It is {this.state.date.toLocaleTimeString()}.

This also works for user-defined components:
這同樣適用用戶(hù)定義的組件中:

The FormattedDate component would receive the date in its props and wouldn"t know whether it came from the Clock"s state, from the Clock"s props, or was typed by hand:
FormattedDate組件將會(huì)接收data作為他的props并且將不知道他是來(lái)自哪,是Clock"s state,是來(lái)自Clock"s state, 還是來(lái)自手動(dòng)輸入的。

function FormattedDate(props) {
  return 

It is {props.date.toLocaleTimeString()}.

; }

打開(kāi)試試

This is commonly called a "top-down" or "unidirectional" data flow. Any state is always owned by some specific component, and any data or UI derived from that state can only affect components "below" them in the tree.
這就是我們平常所說(shuō)的從上往下或者單向數(shù)據(jù)流。任何的state都是屬于一些特定的組件,并且任何的數(shù)據(jù)或者UI視圖 只能影響在他組件樹(shù)下面的的組件。

If you imagine a component tree as a waterfall of props, each component"s state is like an additional water source that joins it at an arbitrary point but also flows down.
如果你把一個(gè)組件的props想象成是瀑布,每一個(gè)組件的state就像一個(gè)額外的水資源,并且這在任意點(diǎn)處鏈接還往下流。

To show that all components are truly isolated, we can create an App component that renders three s:
為了展示所有的組件都是孤立的,我們創(chuàng)建一個(gè)App組件來(lái)渲染三個(gè)組件:

function App() {
  return (
    
); } ReactDOM.render( , document.getElementById("root") );

打開(kāi)試試

Each Clock sets up its own timer and updates independently.
每個(gè)Clock都會(huì)獨(dú)立設(shè)置以及更新自己的定時(shí)器。

In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time.
在React app里,無(wú)論一個(gè)stateful or stateless的組件都被認(rèn)為組件獨(dú)立的細(xì)節(jié)都可能隨著時(shí)間而改變。

You can use stateless components inside stateful components, and vice versa.
你能用stateless組件代替stateful組件,反之亦然。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/81906.html

Failed to recv the data from server completely (SIZE:0/8, REASON:closed)