“GameState”組件上的道具在更改其狀態后無法正確更新,它們始終比 GIF 中顯示的狀態實際值落后一次迭代,而當我嘗試控制臺時,狀態總是落后一次迭代。也記錄它

import GameInfo from './components/GameInfo';
import GameState from './components/GameState';
import InputField from './components/InputField';
import StartButton from './components/StartButton';
import TheWord from './components/TheWord';
import WordsBox from './components/WordsBox';
function App() {
const [currentDifficulty, setCurrentDifficulty] = useState({
time: 7,
wordCount: 15,
});
const changeDifficultyHandler = (difficulty) => {
setCurrentDifficulty(difficulty);
};
return (
<div>
<header>
Type Master
</header>
<main>
<GameInfo onChangeDifficulty={changeDifficultyHandler} />
<TheWord />
<InputField />
<StartButton />
<WordsBox />
<GameState difficulty={currentDifficulty} />
</main>
</div>
);
}
export default App;
import React from 'react';
const GameState = (props) => {
return (
<div>
<div>Time Left: {props.difficulty.time} Seconds</div>
<div>Score: 0 From {props.difficulty.wordCount}</div>
</div>
);
};
export default GameState;
期望值:
const levels = {
Easy: {
time: 7,
wordCount: 15,
},
Normal: {
time: 5,
wordCount: 25,
},
Hard: {
time: 3,
wordCount: 30,
},
};
GameInfo 組件的代碼:
import { useState } from 'react';
const GameInfo = (props) => {
const levels = {
Easy: {
time: 7,
wordCount: 15,
},
Normal: {
time: 5,
wordCount: 25,
},
Hard: {
time: 3,
wordCount: 30,
},
};
const [difficulty, setDifficulty] = useState(levels.Easy);
const changeDifficultyHandler = (event) => {
setDifficulty(levels[event.target.value]);
props.onChangeDifficulty(difficulty);
};
return (
<div>
You Are Playing On The{' '}
<span>
[
<select onChange={changeDifficultyHandler}>
<option value='Easy'>Easy</option>
<option value='Normal'>Normal</option>
<option value='Hard'>Hard</option>
</select>
]
</span>{' '}
Difficulity & You Have{' '}
<span className='text-main font-poppins font-bold'>
[ {difficulty.time} ]
</span>{' '}
Seconds To Type The Word.
</div>
);
};
export default GameInfo;
uj5u.com熱心網友回復:
設定狀態是異步的,所以在changeDifficultyHandler,difficulty中仍然參考舊值,因為它還沒有更新。一個簡單的修復方法是更改props.onChangeDifficulty(difficulty)??為props.onChangeDifficulty(levels[event.target.value]).
也就是說,在兩個地方存盤相同的狀態并不是最佳實踐。為什么不只保留狀態App并將其GameInfo作為道具傳遞給<GameInfo onChangeDifficulty={changeDifficultyHandler} difficulty={currentDifficulty} />?
uj5u.com熱心網友回復:
首先匯入useEffect到您的檔案
import {useEffect} from "react"
然后,
將此添加到您的第一個代碼并嘗試,
useEffect(() => {
}, [props.onChangeDifficulty(difficulty)]);
您已將此添加到您的GameInfo.jsx.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534518.html
