在单击上运行函数会返回陈旧的状态值React Hooks

时间:2019-10-10 19:52:18

标签: reactjs react-hooks use-effect

我正在使用单击时运行特定功能的应用程序中的React Hooks将类组件重构为功能组件。该函数引用状态值,但是该函数中的状态值已过时,这会导致应用崩溃。

我已经在StackOverflow上看到了类似的问题,但是大多数onClick函数只能做一件事,因此使用useRef或useCallback似乎更容易实现。如何确保checkAnswer函数使用更新的状态值?

 const Find = props => {
  const [currentCountry, setCurrentCountry] = useState(null)
  const [guesses, setGuesses] = useState(null)
  const [questions, setQuestions] = useState([])

编辑

在setTurn函数中调用setCurrentCountry挂钩,该挂钩在游戏开始时运行。

  const takeTurn = () => {
            !props.isStarted && props.startGame();
            let country = getRandomCountry();
            console.log(country)
            setGuesses(prevGuess => prevGuess + 1)
            setCurrentCountry(country)
            console.log('setting currentCountry')
            getAnswers(country)
            let nodes = [...(document.getElementsByClassName("gameCountry"))];
            nodes.forEach( node => {
              node.removeAttribute("style")
            })
            if(questions && questions.length === 10){
                console.log('opening modal')
                props.handleOpen();
                // alert("Congrats! You've reached the end of the game. You answered " + props.correct + " questions correctly and " + props.incorrect + " incorrectly.\n Thanks for playing");
                console.log('ending game')
                props.gameOver && endGame();

            }


  const getAnswers = (currentCountry) => {
      console.log(currentCountry)
        let answerQuestions;
        if(questions){
          answerQuestions = [...questions]
        }
        let question = {};
        question['country'] = currentCountry;
        question['correct'] = null;
        let answers = [];
        currentCountry && console.log(currentCountry.name);
        console.log(currentCountry)
        currentCountry && answers.push({
            name: currentCountry.name.split(';')[0],
            correct: 2
        });
        console.log(answers)
        answerQuestions.push(question);
        setQuestions(answerQuestions)
    }
  const checkAnswer = (e, country) => {
        let checkquestions = questions;
        let question = checkquestions.find(question => question.country === currentCountry);
        let checkguesses = guesses;
        console.log(e)
        console.log(country)
        console.log(currentCountry)
        if(!props.isStarted){
          return
        }
        if((country === currentCountry.name || country === currentCountry.name) || guesses === 4){
            props.updateScore(3-guesses);
            console.log(question);
            if(guesses === 1){
                question['correct'] = true;
            }
            checkguesses = null;
            setTimeout(() => takeTurn(), 300);   
        } else {
            question['correct'] = false;
            checkguesses ++
            if(guesses === 3){
              getCountryInfo(e, currentCountry.name);
            }
        }
        setGuesses(checkguesses)
        props.handlePoints(questions);
    }

使用onClick呈现的数据:

          <Geographies  geography={data}>
            {(geos, proj) =>
              geos.map((geo, i) =>
              <Geography
                data-idkey={i}
                onClick={((e) => checkAnswer(e, geo.properties.NAME_LONG))}
                key={i}
                geography={geo}
                projection={proj}
                className="gameCountry"       
              />
            )
            }
          </ Geographies>
          </ZoomableGroup>

该应用程序停止运行,因为currentCountry的状态值仍被读取为null。

0 个答案:

没有答案