React base::
state
梗概
- 每次修改了state都会触发引用了该state的所有组件的组件渲染
hook风格
- use::useState
适用范围
- 与页面显示相关的变量
- 可以不直接显示在变量上,但该state变动了,就意味着页面的内容会发生变动
- 组件的固有状态 ^vedg87
- 组件挂载时创建的状态,并在每次组件渲染中共享
- 而不是每次组件渲染再创建
state的本质
- state并不是一个真正的动态变量,而更像是一个常量
- 每次渲染都会创建一个新的state常量值,而不是修改同一个变量
- 每次渲染中引用state的逻辑会重新执行,从而显得像动态变量一样
- 这种特性是React的响应式渲染机制的基础
注意事项
在React外部使用state
指向原始笔记的链接
在React组件外部(如事件监听器、回调函数)中直接使用state值可能会导致问题
- 外部引用会保留对创建时state值的引用,而非最新值
- 示例:
function Component() { const [count, setCount] = useState(0); useEffect(() => { // 错误方式:直接在外部监听器中使用state document.addEventListener('click', () => { console.log(count); // 永远是创建此监听器时的count值 }); // 正确方式:通过useEffect重新注册监听器 return () => { document.removeEventListener('click', listener); }; }, [count]); // 当count变化时重新注册监听器 }解决方案:
创建state
function MyButton() {
const [count, setCount] = useState(0);
// ...The first time the button is displayed, count will be 0 because you passed 0 to useState().
修改state
直接修改
修改值
示例
When you want to change state, call setCount() and pass the new value to it. Clicking this button will increment the counter:
function handleClick() {
setCount(count + 1);
}修改对象
- when you want to update an object and array, you need to create a new one (or make a copy of an existing one)
- you will use the 拓展运算符 to copy objects and arrays that you want to change
获取最新的state并修改
replacing setScore(score + 1) with setScore(s => s + 1)
示例
console.log(Score)//0
setScore(Score+1)//设置为1
setScore(Score+1)//设置为1- 因为setState的执行时机,所以Score不会立即更新 应该改成这样:
console.log(Score)//0
setScore(s=>s+1)//设置为0+1
setScore(s=>s+1)//设置为1+1注意
- 不能直接修改count,它只是一个值拷贝的变量
setState的执行时机
- child::setState的执行时机
获取state
梗概
- 通过useState拿到的state会响应式更新