深入淺出React的一些細節——State


(來源於: https://facebook.github.io/react/docs/state-and-lifecycle.html 翻譯by:@TimRChen)

Using State Correctly

There are three things you should know about setState().

1.Do Not Modify State Directly

For example, this will not re-render a component:

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

Instead, use setState():

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

The only place where you can assign this.state is the constructor.

2.State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously(異步的), you should not rely on their values for calculating the next state你不應該依賴它們計算的值傳遞給下一個狀態).

For example, this code may fail to update the counter:

// 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接受一個回調函數而不是一個對象). 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:

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

We used an arrow functionES6箭頭函數) above, but it also works with regular functions:

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

The Data Flows Down

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.

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

A component may choose to pass its state down as props to its child components: (一個組件可以選擇將它的state作為props傳遞給它的子組件

<h2>It is {this.state.date.toLocaleTimeString()}.</h2> 

This also works for user-defined(自定義 components:

<FormattedDate date={this.state.date} /> 

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 handFormattedDate組件會在它的props中獲得date,並且不會知道date來自Clock組件的state,還是來自Clock組件的props,或是手動輸入的):

function FormattedDate(props) { return <h2>It is {props.date.toLocaleTimeString()}.</h2>; } 

Try it on CodePen.<——代碼鏈接

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.任何state都屬於具體的組件,任何來自與該state的數據或者UI都只能影響低於該state所在組件下的子組件——>也就是說當前state所在組件默認為父組件

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.假如將組件樹作為props瀑布,每個組件的state就好比加入到整個props瀑布中作為一個任意點的水源,而不是水流

To show that all components are truly isolated相互獨立), we can create an App component that renders three <Clock>s:

function App() { return ( <div>  <Clock />  <Clock />  <Clock /> </div> ); } ReactDOM.render( <App />, document.getElementById('root') ); 

Try it on CodePen. (<——代碼鏈接

Each Clock sets up its own timer and updates independently.(每一個Clock組件建立它們自己的定時器並且互不干擾地進行更新

In React apps, whether a component is stateful or stateless is considered an implementation detail of the component that may change over time. You can use stateless components inside stateful components, and vice versa.你可以使用無狀態的組件在充滿了狀態的組件中,反之亦然

 

總結:今天深入淺出的總結了下關於React中的state使用中的一些細節,以及state與props之間的一些牽連。

ps: 轉載請注明出處。@TimRChen

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM