一、useState的作用
- 在函数组件中的
this指向
在react中是undefined
,使用useState可以使组件state状态
, 并进行状态数据的读写操作 - 作用:给函数组件提供数据
- 语法:
const [xxx, setXxx] = React.useState(initValue)
- useState()说明:
- 参数(initValue): 第一次初始化
指定的值
在内部作缓存 - 返回值([xxx, setXxx]): 包含2个元素的
数组
, 第1个为内部当前状态值
, 第2个为更新状态值的函数
- setXxx()2种写法:
- setXxx(newValue): 参数为非函数值,
直接指定新的状态值
, 内部用其覆盖原来的状态值 - setXxx(value => newValue): 参数为
函数
, 接收原本的状态值, 返回新的状态值, 内部用其覆盖原来的状态值
二、useState的使用
1. 定义组件变量
import React,{useState} from 'react'
const [count, setState] = useState(0)
const [name, setName] = useState('tome')
2. 使用变量{变量名称}
{/* 二、使用变量{变量名称} */}
<h2>当前求和为:{count}</h2>
<button onClick={add}>点我+1</button> <br />
<h2>我的名字是:{name}</h2>
<button onClick={changeName}>点我改名</button>
3. 函数修改state数据 合并操作,执行最后一次
function add(){
setState(count => count+1)
}
const changeName = () => {
setName('jack')
}
4. 合并操作 执行最后一次
setTimeout(()=>{
setState(count+4)
},0)
Promise.resolve().then(res => {
setState(count + 5)
})
三、案例分析
1. 类组件的方法
import React, { Component } from 'react'
export default class Demo extends Component {
state = { count: 1 }
add = () =>{
this.setState( state => ({count:state.count+1}))
}
render() {
return (
<div>
<h1>当前求和为:{this.state.count}</h1>
<button onClick={this.add}>点我+1</button>
</div>
)
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/1ec037a0fc4548e29bea6979f6973369.gif)
3. 函数组件的方法
import React, { useState } from 'react'
export default function Demo() {
const [count, setState] = useState(0)
const [name, setName] = useState('tome')
function add() {
setState(count => count + 1)
}
const changeName = () => {
setName('jack')
}
return (
<div>
{}
<h2>当前求和为:{count}</h2>
<button onClick={add}>点我+1</button> <br />
<h2>我的名字是:{name}</h2>
<button onClick={changeName}>点我改名</button>
</div>
)
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/6fab9901c0184a1fad958022a620dba2.gif)