首页 > 解决方案 > 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]);

控制台截图 在此处输入图像描述

标签: reactjsreact-hooks

解决方案


就是这个:

// 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]);


推荐阅读