useEffect
可以代替的生命周期为 componentDidMount
, componentWillUnMount
和 componentDidUpdate
使用 useEffect
完成 componentDidMount
的效果
function AComponent() {
useEffect(() => {
// TODO
}, []);
}
复制代码
useEffect
的第二个参数为 []
时,表示这个effect只会在 componentDidMount
和 componentWillUnMount
的时候调用
componentWillUnMount
调用的是第一个参数返回的回调
使用 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;
}
复制代码
以上所述就是小编给大家介绍的《React hooks 对应 ClassComponent 中的生命周期与 api》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Google's PageRank and Beyond
Amy N. Langville、Carl D. Meyer / Princeton University Press / 2006-7-23 / USD 57.50
Why doesn't your home page appear on the first page of search results, even when you query your own name? How do other web pages always appear at the top? What creates these powerful rankings? And how......一起来看看 《Google's PageRank and Beyond》 这本书的介绍吧!