简体   繁体   English

无法在自定义挂钩内的回调 function 中访问 state

[英]Can't access state in callback function inside a custom Hook

https://codesandbox.io/s/building-forms-in-react-forked-0n41j?file=/src/index.js https://codesandbox.io/s/building-forms-in-react-forked-0n41j?file=/src/index.js

When I enter text on the input Full Name , and I click on the keywork enter the value of the input still "" on alert popup text.当我在输入Full Name上输入文本时,我单击键输入输入值仍然是 "" 在警报弹出文本上。

look at my code below.看看我下面的代码。

function useKeyPressListener(callback?: Function, keys: string[] = ["Enter"]) {
  const handleClick = (e: any) => {
    if (keys.includes(e.key)) {
      e.preventDefault();
      e.stopPropagation();
      if (callback) callback();
    }
  };

  useEffect(() => {
    console.log("added");
    document.addEventListener("keypress", handleClick);
    return () => {
      console.log("remove");
      document.removeEventListener("keypress", handleClick);
    };
  }, []);
}

const App = () => {
  const [value, setValue] = useState("");

  const submit = () => {
    window.alert(`you submitted value ${value}`);
  };

  useKeyPressListener(submit);
  return (
    <div>
      <div className="col-md-6">
        <h3> Sample Form Container </h3>
        <Input
          inputType={"text"}
          title={"Full Name"}
          name={"name"}
          value={value}
          placeholder={"Enter your name"}
          handleChange={(e) => setValue(e.target.value)}
        />
        <Button action={submit} type={"primary"} title={"Submit"} />
      </div>
      <div>{value}</div>
    </div>
  );
};
document.addEventListener("keypress", handleClick);

is executed once in mount, so it takes the first reference of handleClick function that contain value=""在mount中执行一次,所以它首先引用包含value=""的handleClick function

you should update handleClick when ever handleClick reference change so you can just add [callback] to your useEffect like below你应该在 handleClick 引用更改时更新 handleClick,这样你就可以像下面那样将 [callback] 添加到你的 useEffect

  useEffect(() => {
    console.log("added");
    document.addEventListener("keypress", handleClick);
    return () => {
      console.log("remove");
      document.removeEventListener("keypress", handleClick);
    };
  }, [callback]);

it is fixed here它固定在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM