react 想要更新視圖隻能用 setState( ) 方法
關于 setState() 這裡有三件事情需要知道
1. 不要直接更新狀态, 而是使用 setState()
2. 狀态更新可能是異步的
React 可以将多個setState() 調用合并成一個調用來提高性能。
3. this.props 和 this.state 都可能是異步更新的,你不應該依靠它們的值來計算下一個狀态。
請使用第二種形式的 setState() 來接受一個函數而不是一個對象。
該函數将接收先前的狀态作為第一個參數,将此次更新被應用時的props做為第二個參數
參考官方state
第一種 : 直接 改變
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
msg: "my first react"
};
}
changeHandle = () => {
this.setState({
msg: "我被改變了"
});
};
render() {
return (
<div>
<h1>{this.state.msg}</h1>
<button onClick={this.changeHandle}>改變頁面</button>
</div>
);
}
}
export default App;
第二種 :通過 setState()傳入一個函數,這種用法 用在 你 改變的值,借助于 原有的state裡的預設資料
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
msg: "my first react"
};
}
// 點選事件回調
changeHandle = () => {
// 第一種
// this.setState(state => {
// return {
// msg: "hello"
// };
// });
// 簡寫
this.setState(state => ({ msg: "hello world" }));
};
render() {
return (
<div>
<h1>{this.state.msg}</h1>
<button onClick={this.changeHandle}>改變頁面</button>
</div>
);
}
}
export default App;
舉例 :setState()傳入方法使用場景(假如有這麼個需求,你需要對你渲染的清單資料,點選哪條資料, 哪條資料的icon改變)
安裝了一個 react-icons 圖示庫
import React, { Component } from "react";
import { MdFavorite, MdFavoriteBorder } from "react-icons/md";
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{
id: 1,
title: "學習react",
isLike: false
},
{
id: 2,
title: "學習vue",
isLike: false
},
{
id: 3,
title: "學習NG",
isLike: false
}
]
};
}
handleClick(index) {
this.setState(state => {
state.list[index].isLike = !state.list[index].isLike;
return {
list: state.list
};
});
}
render() {
const { list } = this.state;
return (
<div>
<ul>
{list.map((item, index) => (
<li key={item.id} onClick={() => this.handleClick(index)}>
{item.title}
{item.isLike ? (
<MdFavorite style={{ color: "#f00", marginLeft: 30 }} />
) : (
<MdFavoriteBorder style={{ color: "#f00", marginLeft: 30 }} />
)}
</li>
))}
</ul>
</div>
);
}
}
export default App;