react如何改变state的值
使用 setState 方法
在类组件中,可以通过 this.setState() 方法来更新 state。该方法接收一个对象或函数作为参数,用于合并到当前 state 中。
this.setState({ count: this.state.count + 1 });
如果新 state 依赖于之前的 state,建议使用函数形式:
this.setState((prevState) => ({ count: prevState.count + 1 }));
使用 useState Hook
在函数组件中,可以通过 useState Hook 来定义和更新 state。useState 返回一个 state 变量和一个更新该变量的函数。
const [count, setCount] = useState(0);
setCount(count + 1);
同样,如果新 state 依赖于之前的 state,可以使用函数形式:
setCount((prevCount) => prevCount + 1);
直接修改 state 的注意事项
直接修改 state 的值是无效的,必须通过 setState 或 useState 的更新函数来触发重新渲染。

错误示例:
this.state.count = 1; // 不会触发重新渲染
合并更新与替换更新
setState 是浅合并,只会更新指定的属性,其他属性保持不变。而 useState 的更新函数是完全替换 state。
类组件示例:

this.setState({ count: 1 }); // 其他 state 属性保持不变
函数组件示例:
const [state, setState] = useState({ count: 0, name: 'React' });
setState({ count: 1 }); // name 属性会被替换为 undefined
使用回调处理 state 更新后的操作
如果需要在新 state 生效后执行某些操作,可以在 setState 或 useState 的更新函数后使用回调或 useEffect。
类组件示例:
this.setState({ count: 1 }, () => console.log('State updated'));
函数组件示例:
useEffect(() => {
console.log('State updated', count);
}, [count]);






