使用像UseEffect这样的React钩子的componentDidMount,componentDidUpdate和componentWillUnmount生命周期钩子的等价物是什么?
解决方法
componentDidMount
传递一个空数组作为useEffect()的第二个参数,仅在mount上运行回调.
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()应该足够了.
这answer is inspired by 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的回调参数中返回一个回调函数,它将在卸载之前调用.
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>