useImperativeHandle挂钩不更新值

时间:2019-05-26 08:04:17

标签: reactjs react-hooks

我在我的应用程序中使用useImperativeHandle挂钩向父组件授予值访问权限:

const [phone,setPhone]=useState("");
 useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );

当我使用setPhone更新电话时,值不会更新。我的实现有什么问题?

2 个答案:

答案 0 :(得分:0)

useImperativeHandle需要使组件使用forwardRef,一旦这样做,您就可以访问父项中的更新引用,因为您提供了phone作为其依赖项。

import React, {
  useEffect,
  useState,
  useImperativeHandle,
  forwardRef,
  useRef
} from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = forwardRef((props, ref) => {
  const [phone, setPhone] = useState("");
  useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone
    }),
    [phone]
  );
  useEffect(() => {
    setTimeout(() => {
      setPhone("9898098909");
    }, 3000);
  }, []);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
});

const Parent = () => {
  const appRef = useRef(null);
  const handleClick = () => {
    console.log(appRef.current.value);
  };
  return (
    <>
      <App ref={appRef} />
      <button onClick={handleClick}>Click</button>
    </>
  );
};
const rootElement = document.getElementById("root");
ReactDOM.render(<Parent />, rootElement);

Working demo

答案 1 :(得分:0)

如果您懒惰和/或优化在您的应用程序中还不是非常重要,您可以将 [{}] 的依赖项传递给 useImperativeHandle() 以在每次组件重新渲染时进行更新,确保值始终是最新的。

const App = forwardRef((props, ref) => {
  const [phone, setPhone] = useState("");
  useImperativeHandle(
    ref,
    () => ({
      type: "text",
      name: "phone",
      value: phone,
      // other values that you don't have to keep track of via dependency list
    }),
    [{}]
  );