這是一個帶註釋掉的代碼演示給你更多的信息:http://codepen.io/PiotrBerebecki/pen/rrGWjm
1,什麼是狀態3行?看起來像一個全局變量,它使 感覺它是否在它之前有var或const。這是一個生命週期 函數/ var?
state
第3行只是Counter組件的一個屬性。 REACT使用ES6語法初始化的狀態的另一種方式如下:
constructor() {
super();
this.state = {
value: 0
}
}
陣營文檔:https://facebook.github.io/react/docs/reusable-components.html#es6-classes
的〔陣營ES6類] API是類似與 的例外React.createClass getInitialState。而不是提供一個單獨的getInitialState 方法,您在構造函數中設置您自己的狀態屬性。
2.我必須從反應中導入組件嗎?我記得我 不需要在v15中那樣做。
您也可以只需要導入反應,並以下列方式定義一個類:
import React from 'react';
class Counter extends React.Component {
...
下面也將允許您使用的組件API:
import React, { Component } from 'react';
class Counter extends Component {
...
3.哪裏prevState從哪裏來?
的prevState來自API的setState:https://facebook.github.io/react/docs/component-api.html#setstate
它也可能通過一個函數簽名 功能(狀態,道具)。在某些情況下,如果您想在設置任何值之前讓 排入一個原子更新,該原子更新會查詢以前的狀態+道具值,則此功能可能會有用。例如,假設我們想 狀態遞增值:
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')
);
啊,這是很清楚的感謝!意味着第一號,作者沒有做到「正確」?我可以選擇如果他做'const state = {'value':0}' –
我剛剛添加了正確的方式來初始化我的答案,在問題1下。 –
我看到了,你是說作者做錯了方式?你的意思是什麼?我知道設置構造函數是做東西的常用方法。 –