【问题标题】:How to call function after setState() donesetState() 完成后如何调用函数
【发布时间】:2021-06-01 07:11:57
【问题描述】:

我创建了一个这样的函数。

export function Counter() {

    const [count, setCount] = useState(0);

    const countUp = () => {
        setCount(count + 1);
    }

    const countUpAndShow = () => {
        setCount(count + 1);
        alert(count);
    }

    // I won't call after countUp function, call only countUpAndShow function.
    useEffect(() => {
        alert(count);
    },[count])

    return <div>
        <button onClick={countUp}>count up!</button>
        <button onClick={countUpAndShow}>show count!</button>
    </div>
}

我想在setCount() 之后拨打alert(count)。 但alert(count) 未正确显示计数。

然后,我像上面一样使用useEffect。但我只想调用alert() countUpAndShow 函数。 如何解决?

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    有多种方法可以解决这个问题。我建议使用 React ref 来切换 show“状态”,以便它可以存在于 React 组件生命周期和 React 钩子依赖项之外。我还建议在增加计数器状态值时使用功能更新,因为这将正确地从任何先前的状态与回调入队的状态进行更新。换句话说,它避免了陈旧的状态封闭。

    function Counter() {
      const show = useRef(false);
      const [count, setCount] = useState(0);
    
      const countUp = () => {
        setCount((count) => count + 1);
      };
    
      const countUpAndShow = () => {
        setCount((count) => count + 1);
        show.current = true;
      };
    
      useEffect(() => {
        if (show.current) {
          alert(count);
          show.current = false;
        }
      }, [count]);
    
      return (
        <div>
          <button onClick={countUp}>count up!</button>
          <button onClick={countUpAndShow}>show count!</button>
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      试试这个。

      export function Counter() {
      
          const [count, setCount] = useState(0);
          const [show, setShow] = useState(false);
      
          const countUp = () => {
              setCount(count + 1);
          }
      
          const countUpAndShow = () => {
              setCount(count + 1);
              setShow(true)
              alert(count);
          }
      
          // I won't call after countUp function, call only countUpAndShow function.
          useEffect(() => {
              if(show) {
                  alert(count);
                  setShow(false);
              }
          },[show])
      
          return <div>
              <button onClick={countUp}>count up!</button>
              <button onClick={countUpAndShow}>show count!</button>
          </div>
      }
      
      

      【讨论】:

      • 效果还要依赖count
      • 当前用例不需要。
      • 我同意@thedude,并补充说countUpAndShow 仍然包含不起作用的alert(count);
      • 不是必需的,但无论如何您都应该添加count。事实上,如果你不这样做,`ESLint 会给你一个很大的警告。
      猜你喜欢
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 2019-02-05
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多