【问题标题】:State doesn't always update状态并不总是更新
【发布时间】:2019-07-07 23:00:34
【问题描述】:

useState 中的选择变量并不总是更新。 在下面的代码中,我显示了上下文文件和我的选择组件。上下文文件保存我的反应应用程序的全局状态,并且选择组件通过 setChoices 方法来更新 GameContext 中的状态。我的 setChoices 方法应该更新每个选项的值,但状态只是随机更新,而不是每次更新。

//GameContext file
import React, { createContext, useState } from 'react';

export const GameContext = createContext();

const GameContextProvider = props => {
    const [gameItems, setGameItems] = useState({
        user: {choice: null, score: 0},
        cpu: {choice: null, score: 0}
    })

    const setChoices = (userChoice, cpuChoice) => {
        setGameItems({
            ...gameItems, 
            user:{...gameItems.user, choice: userChoice},
            cpu: {...gameItems.cpu, choice: cpuChoice}
        });  
    }

    const cpuScore = () => {
      setGameItems({
         ...gameItems, 
         cpu:{...gameItems.cpu, score: gameItems.cpu.score + 1}
      })



 return (
        <GameContext.Provider value={{gameItems, setChoices}}>
            { props.children }
        </GameContext.Provider>
    )
}

//choices component
import React, { useContext } from 'react';
import { GameContext } from '../contexts/GameContext';

const Choices = (props) => {

    const {  setChoices } = useContext(GameContext);

    const getCpuChoice = () => {
        const cpuChoices = ['r', 'p', 's'];
        const randomIndex = Math.floor((Math.random() * 3));
        const cpuDecision = cpuChoices[randomIndex];
        return cpuDecision
    }

    const playGame = (e) => {
        const userChoice = e.target.id;
        const cpuChoice = getCpuChoice();

        setChoices(userChoice, cpuChoice);
        cpuScore();
    } 

    return (
            <div>
                <h1>Make Your Selection</h1>
                <div className="choices">
                    <i className="choice fas fa-hand-paper fa-10x" id="p" onClick={playGame}></i>
                    <i className="choice fas fa-hand-rock fa-10x" id="r" onClick={playGame}></i>
                    <i className="choice fas fa-hand-scissors fa-10x" id='s' onClick={playGame}></i>
                </div>
            </div>
        )
    }

我希望用户和 cpu 的选择属性在每次调用 setChoices 时都会更新。我更新状态的方式有问题吗?

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    我做了一些设置来尝试模仿https://codesandbox.io/s/festive-almeida-4zx3c

    可能导致不总是更新的印象是,有时您会因此得到相同的值randomIndex

    如果输出的值与前一个相同,则不会更新。它会认为状态没有改变。

    解决方案:

    强制更新:How can I force component to re-render with hooks in React?

    或者为状态添加一个内部值,它总是会改变,比如哈希。

    【讨论】:

      【解决方案2】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2011-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多