react中的setState方法

在react中如果你想修改数据的话,必须使用this.setState()方法
可以在调用一个事件中使用this.setState()方法,从而达到修改数据的目的, 也可以用于文本框双向数据绑定

例如

render(){
	//创建一个点击事件
	return<button onClick={()=>textCount()}></button>
}
//1. 一般这样写,如果新值依赖旧值的话容易出错,这时我们可以在写成一个函数形式,有两个参数分别为oldState, props,
// 分别代表旧值,和传的值
textCount = ()=>{
	// 里面是一个对象关系
	this.setState({
		count: this.state.count + 1
	})
}

//2. 常用的写法  是一个函数
textCount = ()=>{
	this.setState((oldState, props)=>{
		// 要有一个return, return代表的就是返回的新值
		return{
			count: this.state.count + 1
		}
	})
}

猜你喜欢

转载自blog.csdn.net/zsm4623/article/details/86592121