useEffect
能够代替的生命周期为 componentDidMount
, componentWillUnMount
和 componentDidUpdate
useEffect
完成componentDidMount
的效果function AComponent() {
useEffect(() => {
// TODO
}, []);
}
复制代码
useEffect
的第二个参数为[]
时,表示这个effect只会在componentDidMount
和componentWillUnMount
的时候调用spa
componentWillUnMount
调用的是第一个参数返回的回调code
useEffect
完成componentDidUpdate
的效果function AComponent({source}) {
useEffect(() => {
const subscription = source.subscribe();
// TODO
return () => {
subscription.unsubscribe();
};
}, [source]); // 表示source改变时就是执行一遍
}
复制代码
forceUpdate
function AComponent() {
const [ignored, forceUpdate] = useReducer(x => x + 1, 0);
function handleClick() {
forceUpdate();
}
}
复制代码
getDerivedStateFromProps
function ScrollView({row}) {
let [isScrollingDown, setIsScrollingDown] = useState(false);
let [prevRow, setPrevRow] = useState(null);
if (row !== prevRow) {
// Row changed since last render. Update isScrollingDown.
setIsScrollingDown(prevRow !== null && row > prevRow);
setPrevRow(row);
}
return `Scrolling down: ${isScrollingDown}`;
}
复制代码
props
和 state
function Counter() {
const [count, setCount] = useState(0);
const prevCount = usePrevious(count);
return <h1>Now: {count}, before: {prevCount}</h1>;
}
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
复制代码