React Component的state代表Component的狀態,內容改變時Component會重新渲染(re-render)。
Component的state必須先在Class Component的建構式constructor()初始化屬性值,然後以this.state存取。例如下面在Hello component中初始化state.name,並在render()中以this.state.name取得值。
App.js
import './App.css';
function App() {
const hello = <Hello />
return hello
}
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {name: "John"} // initial state.name value
}
render() {
return (<h1>Hello, {this.state.name}!</h1>)
}
}
export default App;
state和props類似,都是Component中的JavaScript物件屬性,且異動時都會觸發重新渲染。兩者主要差別在於props是由Component外部傳入的參數,例如<Hello name="John"/>且不可從內部改變的(immutable);而state則是在Component內部初始且可從內部改變。
下面示範當Hello.state改變時重新渲染的效果。在Component被render到DOM(又稱為mount)的生命週期方法componentDidMount()中設定setInterval()每秒定時呼叫updateName()並透過setState()更新state.name的內容。
App.js
import React from 'react'
import './App.css';
function App() {
const hello = <Hello />
return hello
}
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {name: "John"} // initial state
}
names = ["John", "Mary", "Tony"]
getRandomName() {
return this.names[Math.floor(Math.random() * this.names.length)]
}
updateName() {
this.setState({name: this.getRandomName()})
}
componentDidMount() {
setInterval(
() => this.updateName(),
1000
);
}
render() {
return (<h1>Hello, {this.state.name}!</h1>)
}
}
export default App;
沒有留言:
張貼留言