react hook

191 阅读1分钟

useState可以将对象设置为初始值,改变属性也会触发hook函数更新

useEffect相当于didmount,didupdate,willunmount

useEffect 中的清除副作用函数相当于willupdate,获取的state是上一个state,并且先于useEffect函数执行

useEffect函数中不能修改state

useEffect先组件函数执行,再执行副作用的清除函数,再执行副作用, 多个副作用函数顺序执行

useEffect函数必须写在最外层, 即生命周期那一层,如果要加条件,在函数内部加

useEffect是面向逻辑编程,将一套逻辑放在一个useeffect函数中,而class是经常需要将一套逻辑分别放在didmount和didupdate中,而didupdate中又有可能有多套多逻辑

通过传递useEffect第二个参数(即依赖项,空数组即只在挂载时执行), 跳过 Effect 进行性能优化

// 原来
componentDidUpdate(prevProps, prevState) {
  if (prevState.count !== this.state.count) {
    document.title = `You clicked ${this.state.count} times`;
  }
}
// 现在
useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // 仅在 count 更改时更新