第一种写法
第一种写法是最简单的写法,就是直接传入一个对象。这种写法是最常用的写法。
this.setState({
message:"你好啊,世界"
})
第二种写法
第二种写法是传入一个回调函数。这种写法是最常用的写法。
this.setState((state,props)=>{
// 1.编写一些对新的State处理逻辑
// 2.可以获取之前的State和props值
console.log(this.state.message,this.props);
return {
message:"你好啊,liying"
}
})
传入回调函数的好处是,可以在回调函数中编写新的State的逻辑。并且当前的回调函数会将之前的State和props传递进来。这样就更方便我们编写新的State的逻辑。真的是yyds。
第三种写法
我们可以在setState
中传入第二个参数:callback。这个参数是一个回调函数。这个回调函数会在数据更新之后(数据合并)执行。如下代码所示:
// 如果希望在数据更新之后(数据合并),获取到对应的结果执行一些逻辑代码
// 那么可以在setState中传入第二个参数:callback
this.setState({message:"你好啊,李银河"},()=>{
console.log("++++++:",this.state.message)
})
console.log("-------:",this.state.message)
然后我们再附上练习的代码,如下所示:
import React,{Component} from "react";
export class App extends Component{
constructor(props){
super(props)
this.state = {
message:"Hello World",
counter:0
}
}
changeText(){
// 1.setState更多用法
// 1.基本使用
// this.setState({
// message:"你好啊,世界"
// })
// 2.setState可以传入一个回调函数
// 好处一:可以在回调函数中编写新的State的逻辑
// 好处二:当前的回调函数会将之前的State和props传递进来
// this.setState((state,props)=>{
// // 1.编写一些对新的State处理逻辑
// // 2.可以获取之前的State和props值
// console.log(this.state.message,this.props);
// return {
// message:"你好啊,liying"
// }
// })
// 3.setState在React的事件处理中是一个异步调用
// 如果希望在数据更新之后(数据合并),获取到对应的结果执行一些逻辑代码
// 那么可以在setState中传入第二个参数:callback
this.setState({message:"你好啊,李银河"},()=>{
console.log("++++++:",this.state.message)
})
console.log("-------:",this.state.message)
}
increment(){
this.setState({
counter:this.state.counter + 1
})
}
render(){
const {message,counter} = this.state;
return (
<div>
<h2>message:{message}</h2>
<button onClick={e=>this.changeText()}>修改文本</button>
<h2>当前计数:{counter}</h2>
<button onClick={e=>this.increment()}>counter+1</button>
</div>
)
}
}
export default App
最后,我们附上运行结果,如下所示:
感谢大家观看,如果觉得不错,欢迎点赞,关注,转发,谢谢大家支持!
of course like your web site but you need to test the spelling on quite a few of your posts. A number of them are rife with spelling problems and I in finding it very troublesome to inform the reality nevertheless I will surely come again again.
新年快乐!
十天看一部剧,还可以吧
@梦不见的梦 行,谢谢提醒,我优化一下
网站的速度有待提升,每次打开都要转半天还进不来呢
@React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?
@Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品
我们大学那会,献血还给学分~
@ab 我想去学网安,比如网警,但分也贼高😕
@夜 加油,你一样也可以成为程序员的,需要学习资料可以V我