反应 useState 不会立即更新

时间:2021-03-24 01:07:06

标签: javascript reactjs react-hooks use-state

我是 React 的新手,只是偶然发现了一个问题,即 useState 不会立即更新。我已经在 stackoverflow 上尝试了答案,但这些答案没有奏效,因为我有多个 useStates,每个 useStates 都包含一个子组件列表。所以使用 useEffect 对我来说不起作用。我的问题是当调用 AIplayCards() 时,useStates 还没有改变。于是AIplayCards()执行,卡片全部为空。

任何帮助将不胜感激!

这是我的代码片段:

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

当其余代码尝试读取 currentPlayerCards 的长度时,返回错误。

1 个答案:

答案 0 :(得分:0)

您应该调用第二个函数作为 setState 的回调,因为 setState 是异步发生的。 所以 --max-tasks-per-child 1 而不是 setState((state, props) => {...})。 如果您发现 useState / setState 没有立即更新,答案很简单:它们只是队列。 React useState 和 setState 不会直接改变 state 对象;他们创建队列以优化性能,这就是更改不会立即更新的原因。