[英]lifecycle event state and prevState in react.js
下面是一個簡單的反擊計數器。 但我有3個問題。
第3行的狀態是什么? 它看起來像一個全局變量,如果它之前有var
或const
就有意義。 這是一個生命周期函數/ var嗎?
我必須從反應中導入組件嗎? 我記得在第15節我不需要這樣做。
prevState來自哪里?
import React, { Component } from 'react'; class Counter extends Component { state = { value: 0 }; increment = () => { this.setState(prevState => ({ value: prevState.value + 1 })); }; decrement = () => { this.setState(prevState => ({ value: prevState.value - 1 })); }; render() { return ( <div> {this.state.value} <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> </div> ) } }
這是一個帶有注釋掉代碼的演示,為您提供更多信息: http : //codepen.io/PiotrBerebecki/pen/rrGWjm
1.第3行的狀態是什么? 看起來像一個全局變量,如果它之前有var或const就有意義。 這是一個生命周期函數/ var嗎?
第3行中的state
只是Counter組件的屬性。 使用ES6語法在React中初始化狀態的另一種方法如下:
constructor() {
super();
this.state = {
value: 0
}
}
反應文檔: https : //facebook.github.io/react/docs/reusable-components.html#es6-classes
[React ES6 class] API類似於React.createClass,但getInitialState除外。 您可以在構造函數中設置自己的state屬性,而不是提供單獨的getInitialState方法。
2.我是否必須從反應中導入組件? 我記得我不需要在第15節那樣做。
您也可以通過以下方式導入React並定義類:
import React from 'react';
class Counter extends React.Component {
...
下面還允許您使用組件API:
import React, { Component } from 'react';
class Counter extends Component {
...
3. prevState來自哪里?
prevState來自setState api: https ://facebook.github.io/react/docs/component-api.html#setstate
也可以使用簽名函數(state,props)傳遞函數。 在某些情況下,當您想要在設置任何值之前將參與state + props的先前值的原子更新排入隊列時,這可能很有用。 例如,假設我們想要增加狀態值:
this.setState(function(previousState, currentProps) {
return {
value: previousState.value + 1
};
});
您經常會看到開發人員以下列方式更新狀態。 這不如上述方法可靠,因為狀態可以異步更新,我們不應該依賴其值來計算下一個狀態。
this.setState({
value: this.state.value + 1 // prone to bugs
});
我的codepen的完整代碼:
class Counter extends React.Component {
// state = { value: 0 };
// you can also initialise state in React
// in the constructor:
constructor() {
super();
this.state = {
value: 0
}
}
increment = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
}
decrement = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
}
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
ReactDOM.render(
<Counter />,
document.getElementById('app')
);
您的代碼中有一些與ES6(ES2015)版本相關的功能,這就是您可能會感到困惑的原因:
第3行的狀態是什么? 看起來像一個全局變量,如果它之前有var或const就有意義。 這是一個生命周期函數/ var嗎?
由於它位於class
體內,因此它不是全局變量。 在這種情況下, state
是一個將設置為Counter
實例的屬性,因此您可以通過this.state
訪問它。
我必須從反應中導入組件嗎? 我記得我不需要在第15節那樣做。
使用類創建組件時,需要擴展Component
類,因此在這種情況下:是的,您需要導入Component
或者您可以使用class Counter extends React.Component
也可以class Counter extends React.Component
。
prevState來自哪里?
再一次,ES6功能。 傳遞給this.setState()
方法的是一個函數 。 這可能會令人困惑,因為這是一個箭頭函數=>
。 所以previousState
實際上是該函數的一個參數。 為了幫助您查看圖片,上面的代碼類似於 :
this.setState(function (prevState) {
return {
value: prevState.value - 1
};
});
但是,“普通”和箭頭功能之間存在一些差異,因此我建議您搜索ES6功能以便更熟悉它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.