亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 React 功能掛鉤在異步操作后獲取更改的狀態

如何使用 React 功能掛鉤在異步操作后獲取更改的狀態

陪伴而非守候 2022-10-08 17:20:44
如何使用 React 功能掛鉤在異步操作后獲取更改的狀態?我找到了針對這個問題的 redux 解決方案,或者 react 類組件解決方案,但我想知道是否有一個簡單的 react 功能解決方案。這是場景:創建一個功能性的反應組件。幾個州創建幾個按鈕元素,每個元素都會改變不同的狀態。使用其中一個按鈕元素,觸發異步操作。如果狀態有任何其他變化,在從異步函數接收結果之前,中止所有其他繼續操作。附上代碼沙箱示例 https://codesandbox.io/s/magical-bird-41ty7?file=/src/App.js
查看完整描述

4 回答

?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

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>


查看完整回答
反對 回復 2022-10-08
?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

您可以使用 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


查看完整回答
反對 回復 2022-10-08
?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

正如@thedude 所提到的,您將需要使用useRef鉤子——它是為您的用例而制作的,正如文檔所說:“它可以方便地保留任何可變值,類似于您在類中使用實例字段的方式?!?/p>


我想你可能只想添加一個簡單的 boolean:


  const counterChanged = useRef(false);

然后當你更新計數器時,你也會更新它。


            counterChanged.current = true;

            setCounter(counter + 1);

在您的 async 函數中,將其設置為 false ,然后檢查它是否已更改。


counterChanged.current = false;

            await new Promise(resolve => {

              setTimeout(() => {

                resolve();

              }, 4000);

            });

            if (counterChanged.current) {

            // alert


查看完整回答
反對 回復 2022-10-08
?
蝴蝶刀刀

TA貢獻1801條經驗 獲得超8個贊

通過在 facebook-rect github 上提問,我找到了另一個答案。顯然,由于設置狀態是一個函數,它的第一個參數是當前狀態。


因此可以在設置計數器值時使用此代碼段訪問先前的值:


 setCounter(prevValue => {

          alert(prevValue + " " + counter);

          return counter + 1;

        });

https://github.com/facebook/react/issues/19270 https://reactjs.org/docs/hooks-reference.html#functional-updates


查看完整回答
反對 回復 2022-10-08
  • 4 回答
  • 0 關注
  • 205 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號