reactjs - React useEffect:为什么我的值最初是未定义的?
问题描述
我正在尝试设置一个 onKeyPress 事件侦听器,但我很困惑为什么初始值是未定义的,然后是我想要的值。数据在挂载时添加(参见x
控制台)。为什么我不能立即捕获它,而是得到一个 initial undefined
,特别是因为它显然已经存在于 state 中?
useEffect(() => {
console.log('x', multipleChoice); <-- logs the array of objects
const handleKeyPress = ({ key }) => {
const index = Number(key) - 1;
if (key === '1') {
console.log(multipleChoice[index]); <-- logs undefined, then logs object
}
};
window.addEventListener('keydown', (e) => handleKeyPress(e));
return () => {
window.removeEventListener('keydown', (e) => handleKeyPress(e));
};
}, [allCards, currentCard, multipleChoice]);
本地状态
const [currentCard, setCard] = useState(0);
const [multipleChoice, setMultipleChoice] = useState([]);
// allCards is passed as a prop on page load from the parent
当用户猜对答案时,currentCard 加 1
设置 multipleChoice 的 UseEffect
useEffect(() => {
const generateMultipleChoice = (words: Word[]) => {
const possibleAnswers = words.reduce(
(accum: Word[]) => {
while (accum.length < 4) {
// randomly select words from pool
const index = getRandomInt(0, allCards.length - 1);
const randomWord = allCards[index];
// verify current hand doesn't already have that word
if (!accum.includes(randomWord)) {
accum.push(randomWord);
}
}
return accum;
},
// default with the current card already in the hand
[allCards[currentCard]]
);
// return the hand with the matching card and (3) other cards from pool
return possibleAnswers;
};
const shuffledCards = shuffle(generateMultipleChoice(allCards));
setMultipleChoice(shuffledCards);
}, [allCards, currentCard]);
解决方案
就是这个:
// initial state
const [multipleChoice, setMultipleChoice] = useState([]);
// therefore, initially, if index is any Number
console.log(multipleChoice[index]) // undefined
返回对象,直到计算完成...
useEffect(() => {
// ...
// this has to run before `multipleChoice` is updated to return that object
const shuffledCards = shuffle(generateMultipleChoice(allCards));
setMultipleChoice(shuffledCards);
}, [allCards, currentCard]);
推荐阅读
- python - 在 Maya 中,我可以阻止动画曲线节点读取吗?
- laravel - 给定一组用户名,我如何从 Laravel 的模型中只检索他们的详细信息?
- codeception - 是否可以在 _failed() 挂钩中获取失败测试的文件名?
- spring-boot - SpringBoot Actuator 日志文件端点返回 404
- r - 重新编码(汽车)无法将 NA 转换为 0 并将值转换为 1
- reactjs - 从同一功能设置禁用道具和焦点的问题
- angular - 如何知道子组件是否在 Angular 中加载
- angular - 在 Angular 9 中提交表单后没有得到任何控制台日志
- neural-network - 有没有办法将可变数量的图像传递给 CNN
- recaptcha-v3 - 验证码 3 和经典 ASP