Open ThenMorning opened 4 years ago
class Foo{
it = 0;
}
function Foo(){
const it = useRef(0);
}
function Foo() {
const [count, setCount] = useState(0);
const oldCount = useRef();
useEffect(() => {
oldCount.current = count;
});
return (
<div>
now:{count}, old:{oldCount.current}
<div>
<button
onClick={() => {
setCount(count + 1);
}}
>
add
</button>
</div>
</div>
);
}
在Hooks组件中使用一个与渲染无关的state,setState即可
useState处理状态 useEffect处理副作用 useContext处理跨层级传值 useMemo,useCallback处理幂等计算 useRef保存引用
不会
1.生命周期函数如何映射到Hooks?
constructor:
class component 会在其中初始化state hooks 可以直接使用 useState初始化state
getDerivedStateFromProps:(从props中获取state,替代componentWillReceiveProps)
class component 会在其中做一些props到state的映射 hooks可以直接在函数体中使用setState方法,如下
shouldComponentUpdate
class component 会在其中做一些props或state的判断用来减少组件的重新渲染 hooks可以使用memo
render
略
componentDidMount , componentWillUnMount , componentDidUpdate
getSnapshotBeforeUpdate,componentDidCatch, getDerivedStateFromError
暂时还无法用hooks实现