函数组件
创建方式
const Hello = (props) => {
return <div>{props.message}</div>
}
const Hello = props => <div>{props.message}</div>
function Hello(props){
return <div>{props.message}</div>
}
函数组件代替class组件
- 面临的两个问题: 函数组件没有state(Hooks API中的一个叫做useState可以解决问题),函数组件没有声明周期(Hooks API中的一个叫做useEffect可以解决问题)
useEffect
模拟 componentDidMount
useEffect(()=>{ console.log('第一次渲染')},[])
[]代表着只在第一次渲染时调用
模拟 componentDidUpdate
-
useEffect(()=>{ console.log('任意属性变更')}) -
useEffect(()=>{ console.log('n变了')}, [n])
模拟 componentWillUnmount
useEffect(()=>{
console.log('第一次渲染')
return ()=>{
console.log('组件要死了')
}
})
其他生命周期怎么模拟
constructor
- 函数组件执行的时候,就相当于constructor
shouldComponentUpdate
- 后面的React.memo和useMemo可以解决
render
- 函数组件的返回值就是render的返回值
插曲: useUpdate
App.js
import React, { useEffect } from "react";
import useUpdate from "./useUpdate.js";
const App = (props) => {
const [n, setN] = useState(0);
const onClick = () => {
setN(n + 1);
};
useUpdate(() => {
console.log("变了");
}, n);
return (
<div>
{n}
<button onClick={onClick}>+1</button>
</div>
);
};
export default App;
useUpdate.js
const useUpdate = (fn, dep) => {
const [count, setCount] = useState(0);
useEffect(() => {
setCount((x) => x + 1);
}, [dep]);
useEffect(() => {
if (count > 1) {
fn();
}
}, [count, fn]);
};
export default useUpdate;