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;