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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- FreeMarker对应各种数据结构解析
- Vue和MVVM的对应关系
- nhibernate一表对应多个实体类问题
- 调试V8中JS对应的汇编代码
- 二分查找及对应的几道经典题目
- 二分查找及对应的几道经典题目
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Impractical Python Projects
Lee Vaughan / No Starch Press / 2018-11 / USD 29.95
Impractical Python Projects picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you’ll use every day. And to keep things interesting, ea......一起来看看 《Impractical Python Projects》 这本书的介绍吧!