仅在使用useEffect卸载组件时执行功能

时间:2020-07-14 23:35:44

标签: javascript reactjs react-hooks

我正在尝试使用useState在函数内部运行带有useCallback的变量的函数

仅当使用return钩中的useEffect卸载组件时,此功能才应运行:

import React, { useEffect, useCallback, useState } from "react";
import "./styles.css";

export default function App() {
  const [search, setSearch] = useState("");

  const update = useCallback(() => {
    console.log({ search });
  }, [search]);

  useEffect(() => {
    return () => {
      update();
      console.log("I ONLY WANT THIS TO RUN ON UNMOUNT");
    };
  }, [update]);

  return (
    <div className="App">
      <input defaultValue={search} onChange={e => setSearch(e.target.value)} />
    </div>
  );
}

https://codesandbox.io/s/react-useeffect-btrbi?file=/src/App.js

0 个答案:

没有答案