2021年3月23日星期二

React useState not updating immediately

I'am new to React and just stumbled upon a problem where useState does not update immediately. I've tried answers on stackoverflow but those did not work out because I have multiple useStates that each comprises a list of children components. So using useEffect does not do the trick for me. The problem for me is that when AIplayCards() is called, useStates aren't changed yet. So then AIplayCards() executes, the cards are all null.

Any help would be appreciated!

Here is my code snippet:

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.      }  

Just for reference purpose:

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

When the rest of the code attempts to read the length of currentPlayerCards, an error is returned.

https://stackoverflow.com/questions/66773383/react-usestate-not-updating-immediately March 24, 2021 at 09:07AM

没有评论:

发表评论