简体   繁体   English

如何用数组填充状态

[英]How to fill a state with an array

I'm trying to add a list inside a state using the set method, but my state remains empty我正在尝试使用 set 方法在状态内添加列表,但我的状态仍然为空

App.js应用程序.js

// Starts the screts word game
  const startGame = () => {
    // pick word and pick category
    const { word, category } = pickWordAndCategory();
    // create array of letters
    let wordLetters = word.split("");
    wordLetters = wordLetters.map((l) => l.toLowerCase());

    // Fill states
    setPickedCategory(category);
    setPickedWord(word);
    setLettersList(wordLetters);
    console.log('wordLetters', wordLetters);
    console.log('lettersList', lettersList);
    

    setGameState(stages[1].name);
  };

  const pickWordAndCategory = () => {
    // pick a random category
    const categories = Object.keys(words);
    const category = categories[Math.floor(Math.random() * Object.keys(categories).length)];
    console.log('category', category);

    // pick a random word
    const word = words[category][Math.floor(Math.random() * words[category].length)]
    console.log(word);

    return { word, category };
  }

Here is the browser log这是浏览器日志

When looking at the log we find our state empty查看日志时,我们发现我们的状态为空

States updates are asynchronous, so when you set a new state value and console.log() right after it, it's going to show the previous value, because the state hasn't been updated yet.状态更新是异步的,所以当你设置一个新的状态值和 console.log() 之后,它会显示以前的值,因为状态还没有更新。

That's why your lettersList value show the old value of the state in the console (empty array).这就是为什么您的lettersList值在控制台中显示状态的旧值(空数组)。

When you use setLettersList(...) , you are not actually changing lettersList variable itself.当您使用setLettersList(...)时,您实际上并没有更改lettersList变量本身。 Notice how when you declare it, const [lettersList, setLettersList] = useState([]);注意当你声明它时, const [lettersList, setLettersList] = useState([]); letterList is actually constant, so that variable can't even be changed. letterList实际上是常量,因此该变量甚至无法更改。 Instead, it tells React to rerun the function component, this time giving lettersList the new value.相反,它告诉 React 重新运行函数组件,这次给lettersList一个新值。 Therefore, for the updated value, it will only come once const [lettersList, setLettersList] = useState([]);因此,对于更新的值,它只会出现一次const [lettersList, setLettersList] = useState([]); is rerun again from the entire function being rerun again.从重新运行的整个函数再次重新运行。

If you want to monitor changes to lettersList, you can do:如果要监视对 lettersList 的更改,可以执行以下操作:

useEffect(() => {
  console.log(lettersList);
}, [lettersList]);

This will print lettersList every time it is updated.这将在每次更新时打印 lettersList 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM