为什么必须调用两次函数才能更新挂钩状态?

时间:2020-01-14 11:56:33

标签: javascript reactjs react-hooks

我正在尝试实现以下是/否按钮:

import React, { useState } from "react";

const YesNoComponentFunctional = () => {
  const [button, setButton] = useState("");

  const onYesPress = () => {
    setButton("Yes");
    console.log({ button });
  };

  const onNoPress = () => {
    setButton("No");
    console.log({ button });
  };

  return (
    <div>
      <button onClick={() => onYesPress()}>Yes</button>
      <button onClick={() => onNoPress()}>No</button>
     </div>
  );
};
export default YesNoComponentFunctional; 

我从这个article here中学到了。

我不明白为什么我必须单击两次按钮才能正确显示要控制台的消息。为什么会这样?

2 个答案:

答案 0 :(得分:3)

setButton是异步方法,您的按钮状态不会立即更新。 您可以使用useEffect挂钩检查按钮的值是否已更新。

useEffect(() => {
  console.log({button});
}, [button]);

答案 1 :(得分:1)

set函数(此示例为setButton)是异步的。为了获得准确的结果,您需要使用useEffect。

import React, { useState, useEffect } from "react";

const YesNoComponentFunctional = () => {
  const [button, setButton] = useState("");

  const onYesPress = () => {
    setButton("Yes");
  };

  const onNoPress = () => {
    setButton("No");
  };
  
  useEffect(() => {
    console.log({button})
  }, [button])

  return (
    <div>
      <button onClick={() => onYesPress()}>Yes</button>
      <button onClick={() => onNoPress()}>No</button>
     </div>
  );
};
export default YesNoComponentFunctional;