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 */
});
网友评论