react hook

hook是在用function创建component后 处理state 以及生命周期的方法

import React, { useState, useEffect } from 'react';

const App = (props) => {
  const [count, setCount] = useState(0)

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  })

  // componentWillUnmount
  // componentDidMount() {
  //   document.title = `You clicked ${this.state.count} times`;
  // }
  //
  // componentDidUpdate() {
  //   document.title = `You clicked ${this.state.count} times`;
  // }

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default App;

useState()combined initialize state and setState
useEffect() combined three lifecycle functions componentDidMount() and componentDidUpdate() and componentWillUnmount()

要单独控制componentDidUpdate()时,可以在useEffect()加入第二个参数,空数组[]或者相应变化的数组变量[count]

要单独控制componentWillUnmount()时,在useEffect()里最后return一个function,return的内容就是Unmount()的内容
—————————————————————————————————————————
React.memo是用于优化性能 当funtion component 里 props change的时候 才会重新render

const MyComponent = React.memo(function MyComponent(props) {
  /* only rerenders if props change */
});
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容