函数组件没有自己的state和生命周期,又叫无状态组件,没有自己的state,所以也可以将之称之为展示型组件
如何使用useState:
usestate是一个hook,该hook允许我们在函数组件中使用state
必须在函数组件内部使用
- 通过usestate在函数组件中写了一个state
- count表示state
- setCount修改state的方法
import React,{FC,useState} from "react"
// Fc是函数组件的类型
type IPorps={
name:string,
age:number
}
const Say:FC<IPorps> = (props) => {
//通过usestate在函数组件中写了一个state
//count表示state
//setCount修改state的方法
let [count,setCount]=useState<number>(0)
const clickHandler=()=>{
setCount(++count);
}
return <div>
这是一个函数组件{props.name}
当前的count是:{count}
<button onClick={clickHandler}>点我修改count</button>
</div>
}
export default Say
修改state之后无法拿到最新的状态,要等到下一个事件循环周期执行时,状态才是最新的
import { stringify } from "querystring"
import React,{FC,useState} from "react"
// Fc是函数组件的类型
type IPorps={
name:string,
age:number
}
const Say:FC<IPorps> = (props) => {
//通过usestate在函数组件中写了一个state
//count表示state
//setCount修改state的方法
const [people,setPeople]=useState<{name:string;age:number}>({
name:"wangsu",
age:23
})
const clickHandler1=()=>{
setPeople({
name:"yeye",
age:18
})
console.log(people.name)
}
return <div>
这个的年龄是:{people.age},姓名是:{people.name}
<button onClick={clickHandler1}>点我修改姓名</button>
</div>
}
export default Say
解决办法是同步在写一遍
const clickHandler1=()=>{
setPeople({
name:"yeye",
age:18
})
//在写一遍,设置name
people.name="yeye";
}
注意点一:
usestate的数据不是合并,而是用一个新的数组去替换掉原来的数据
import { stringify } from "querystring"
import React,{FC,useState} from "react"
// Fc是函数组件的类型
type IPorps={
name:string,
age:number
}
const Say:FC<IPorps> = (props) => {
const [people,setPeople]=useState<{name?:string;age?:number;gender?:string}>({
name:"wangsu",
age:23
})
const clickHandler=()=>{
setCount(++count);
}
const clickHandler1=()=>{
setPeople({
gender:"男"
})
}
return (<div>
{people.gender}
{console.log(people)}//这里的结果是:{gender: "男"}
<button onClick={clickHandler1}>点我修改姓名</button>
</div>)
}
export default Say
注意点二:
useState
中的数据务必是immutable
数据
不能在原来基础上进行修改,要完全换一个对象,内存地址发生改变才能触发页面进行刷新
import React, { FC, useState } from "react";
// Fc是函数组件的类型
type IPorps = {
name: string;
age: number;
};
const Say: FC<IPorps> = (props) => {
//通过usestate在函数组件中写了一个state
//count表示state
//setCount修改state的方法
let [count, setCount] = useState<number>(0);
const [people, setPeople] = useState<{
name?: string;
age?: number;
gender?: string;
}>({
name: "wangsu",
age: 23,
});
const [list, setList] = useState<number[]>([
1,
3,
5,
2,
13,
9,
45,
30,
2,
50,
4,
]);
const clickHandler = () => {
setCount(++count);
};
const clickHandler1 = () => {
setPeople({
gender: "男",
});
};
const clickHandler2 = () => {
list.sort((a, b) => {
return a - b;
});
//这里触发了内存地址发生改变
setList([...list])
};
return (
<div>
{people.gender}
{list}
{console.log(people)}
<button onClick={clickHandler}>点我修改count</button>
<button onClick={clickHandler1}>点我修改姓名</button>
<button onClick={clickHandler2}>点我进行排序</button>
</div>
);
};
export default Say;