gpt4 book ai didi

javascript - 如何使用 React 功能 Hook 在异步操作后获取更改的状态

转载 作者:行者123 更新时间:2023-12-01 15:03:21 31 4
gpt4 key购买 nike

如何使用 React 功能 Hook 在异步操作后获取更改的状态?我已经找到了针对这个问题的 redux 解决方案,或者 react 类组件解决方案,但我想知道是否有一个简单的 react 功能解决方案。
这是场景:

  • 创建一个功能性的 react 组件。少数州
  • 创建几个按钮元素,每个元素都会改变不同的状态。
  • 使用其中一个按钮元素,触发异步操作。
  • 如果状态有任何其他变化,在从异步函数接收结果之前,中止所有其他继续操作。

  • 附上一个代码沙箱示例
    https://codesandbox.io/s/magical-bird-41ty7?file=/src/App.js

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

    export default function App() {
    const [counter, setCounter] = useState(0);
    const [asyncCounter, setAsyncCounter] = useState(0);
    return (
    <div className="App">
    <div>
    <button
    onClick={async () => {
    //sets the asyncCounter state to the counter states after a 4 seconds timeout
    let tempCounter = counter;
    await new Promise(resolve => {
    setTimeout(() => {
    resolve();
    }, 4000);
    });
    if (tempCounter !== counter) {
    alert("counter was changed");
    } else {
    setAsyncCounter(counter);
    }
    }}
    >
    Async
    </button>
    <label>{asyncCounter}</label>
    </div>
    <div>
    <button
    onClick={() => {
    //increases the counter state
    setCounter(counter + 1);
    }}
    >
    Add 1
    </button>
    <label>{counter}</label>
    </div>
    </div>
    );
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    最佳答案

    您可以使用 ref 独立跟踪计数器值

     const [counter, setCounter] = useState(0);
    const counterRef = useRef(counter)
    每当您更新 counter 时,您也会更新 counterRef:
    const newCounter = counter + 1
    setCounter(newCounter);
    counterRef.current = newCounter
    然后检查它:
    if (counterRef.current !== counter) {
    alert("counter was changed");
    } else {
    setAsyncCounter(counter);
    }
    Codesandox

    关于javascript - 如何使用 React 功能 Hook 在异步操作后获取更改的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62424530/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com