簡體   English   中英

反應 useState 沒有立即更新

[英]React useState not updating immediately

我是 React 的新手,只是偶然發現了 useState 不會立即更新的問題。 我已經嘗試過有關 stackoverflow 的答案,但沒有解決,因為我有多個 useState,每個都包含一個子組件列表。 所以使用 useEffect 對我來說沒有用。 對我來說,問題是當 AIplayCards() 被調用時, useStates 還沒有改變。 所以然后AIplayCards()執行,卡都是null。

任何幫助,將不勝感激!

這是我的代碼片段:

const Game = (props) => {
    const [mounted, setMounted] = useState(false)
    const [playerCards, setPlayerCards] = useState([])
    const [opponentLeftCards, setOpponentLeftCards] = useState([])
    const [startingTurn,setStartingTurn] = useState(true)
    const [turn, setTurn] = useState(null)

    useEffect(() => {
        resetGame();
        //componentWillMount
        setMounted(true)
    }, []);
    
    useEffect(() => {
        if(mounted){
            if (turn !== "player") AIplayCards()
        }
    }, [mounted]);
    //My effort to make it work

    const resetGame = async () => {
        let deck = Rules.newDeck()
        let playerCards = await Rules.setUserCards(deck)
        let opponentLeftCards = await Rules.setUserCards(deck)
        let firstTurn = Rules.setFirstTurn(playerCards, opponentLeftCards, opponentTopCards, opponentRightCards)
        //Works

        setPlayerCards(playerCards)
        setOpponentLeftCards(opponentLeftCards)
        setTurn(firstTurn)
        setStartingTurn(true)
        //here if I console.log the states and they arent changed yet.
    }

僅供參考:


    const AIplayCards = () => {
        let currentPlayerCards = getCardsforTurn()
        //returns null because turn is still null, and it match with none of the the if statements in getCardsforTurn. 
          ......

當代碼的rest嘗試讀取currentPlayerCards的長度時,返回錯誤。

您應該調用第二個 function 作為 setState 的回調,因為 setState 是異步發生的。 所以setState((state, props) => {...})而不是setState(object) 如果您發現 useState / setState 沒有立即更新,答案很簡單:它們只是隊列。 React useState 和 setState 不會直接對 state object 進行更改; 他們創建隊列以優化性能,這就是更改不會立即更新的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM