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;
}
複製代碼