组件状态
分类 | Hooks | Classes |
---|---|---|
声明 | useState() v16.8 | state ES2022 |
读取 | - | this.state v0.13 |
更新 | set v16.8 | this.setState(nextState, callback?) v0.13 |
\- | useReducer() v16.8 | - |
监听 | useEffect() v16.8 | - |
\- | useLayoutEffect() v16.8 | - |
\- | useEffectEvent() | - |
\-CSS-in-JS | useInsertionEffect() v18.0 | - |
大纲
- 状态
- 声明
- 初始值
- 默认值来源
- 初始化函数-避免重复创建初始状态
- 初始值
- 读取
- 更新
- 派生状态/计算
- 更新后立即获取
- setState(() => )
- 保存变量中
- 状态变更立即更新 DOM
- 更新状态中的对象和数组
- 不可变数据,替换
- 扩展符 ...
- 性能优化
- 避免重复创建初始状态
- 使用 key 重置状态
- 存储前一次渲染的信息
- 监听
- 异步监听
- 同步监听
- 深度监听和立即执行
- 监听依赖自动收集
- 声明
状态声明
- useState()
constructor()
state
- Hooks
- Classes
// https://zh-hans.react.dev/reference/react/Component#migrating-a-component-with-state-from-a-class-to-a-function
// https://zh-hans.react.dev/learn/state-a-components-memory
// https://zh-hans.react.dev/learn/state-as-a-snapshot
// https://zh-hans.react.dev/learn/queueing-a-series-of-state-updates
// https://zh-hans.react.dev/learn/reacting-to-input-with-state
// https://zh-hans.react.dev/learn/preserving-and-resetting-state
// https://zh-hans.legacy.reactjs.org/docs/faq-state.html
// https://zh-hans.react.dev/learn/updating-objects-in-state
// https://zh-hans.react.dev/learn/updating-arrays-in-state
// https://zh-hans.react.dev/reference/react/Component#adding-state-to-a-class-component
状态读取
- [state]
this.state
- Hooks
- Classes
状态更新
- [setState]
this.setState()
- Hooks
- Classes
派生状态(计算)
- useReducer()
static getDerivedStateFromProps()
你正设置的状态是从某个其他状态变量的先前状态计算出的,则你可能希望将它们结合成一个对象然后 使用 reducer。
- Hooks
- Classes
// https://zh-hans.react.dev/learn/extracting-state-logic-into-a-reducer