栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

React Hook和等效组件生命周期

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

React Hook和等效组件生命周期

componentDidMount

传递一个空数组作为第二个参数,

useEffect()
以仅在安装时仅运行回调。

function ComponentDidMount() {  const [count, setCount] = React.useState(0);  React.useEffect(() => {    console.log('componentDidMount');  }, []);  return (    <div>      <p>componentDidMount: {count} times</p>      <button        onClick={() => {          setCount(count + 1);        }}      >        Click Me      </button>    </div>  );}ReactDOM.render(  <div>    <ComponentDidMount />  </div>,  document.querySelector("#app"));<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script><div id="app"></div>

componentDidUpdate

componentDidUpdate()
更新发生后立即调用。初始渲染不调用此方法。
useEffect
在每个渲染(包括第一个)上运行。因此,如果要使用严格等同于
componentDidUpdate
,则必须使用
useRef
确定组件是否已安装一次。如果您想要更严格,请使用
useLayoutEffect()
,但它会同步触发。在大多数情况下,
useEffect()
应该足够了。

这个答案受到Tholle的启发,所有功劳归他所有。

function ComponentDidUpdate() {  const [count, setCount] = React.useState(0);  const isFirstUpdate = React.useRef(true);  React.useEffect(() => {    if (isFirstUpdate.current) {      isFirstUpdate.current = false;      return;    }    console.log('componentDidUpdate');  });  return (    <div>      <p>componentDidUpdate: {count} times</p>      <button        onClick={() => {          setCount(count + 1);        }}      >        Click Me      </button>    </div>  );}ReactDOM.render(  <ComponentDidUpdate />,  document.getElementById("app"));<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script><div id="app"></div>

componentWillUnmount

在useEffect的callback参数中返回一个回调,它将在卸载之前被调用。

function ComponentWillUnmount() {  function ComponentWillUnmountInner(props) {    React.useEffect(() => {      return () => {        console.log('componentWillUnmount');      };    }, []);    return (      <div>        <p>componentWillUnmount</p>      </div>    );  }  const [count, setCount] = React.useState(0);  return (    <div>      {count % 2 === 0 ? (        <ComponentWillUnmountInner count={count} />      ) : (        <p>No component</p>      )}      <button        onClick={() => {          setCount(count + 1);        }}      >        Click Me      </button>    </div>  );}ReactDOM.render(  <div>    <ComponentWillUnmount />  </div>,  document.querySelector("#app"));<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script><div id="app"></div>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/409800.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号