在反应应用程序中从数组中删除单词的最佳方法

问题描述 投票:0回答:1

我正在使用 React 开发一个快速打字游戏,我有一个函数可以在跳过或正确输入单词后从数组中删除单词。我认为有一种更好的方法可以通过创建一个新数组/不直接从我的单词数组中删除它来做到这一点,但我在实现上有点卡住。重构删除单词功能的最佳方法是什么?

import wordsArray from "./components/wordsArray";

export default function App() {
  const getRandomWord = () => {
    return wordsArray[Math.floor(Math.random() * wordsArray.length)];
  };
  const [word, setWord] = useState(getRandomWord());
  const removeWord = () => {
    const removedWordIndex = wordsArray.indexOf(word);
    wordsArray.splice(removedWordIndex, 1);
    if (wordsArray.length === 0) {
      setGameOver(true);
    }
  };
}
reactjs arrays splice
1个回答
0
投票

我认为你应该使用状态来表示单词列表。

import wordsArray from "./components/wordsArray";

export default function App() {
  const getRandomWord = () => {
    return wordsArray[Math.floor(Math.random() * wordsArray.length)];
  };
  const [word, setWord] = useState(getRandomWord());
  const [wordlist, setWordlist] = useState(wordsArray);

  const removeWord = () => {
    const updatedWordlist = wordlist.filter(w => w !== word);
    setWordlist(updatedWordlist);
    if (updatedWordlist.length === 0) {
      setGameOver(true);
    }
  };
}
© www.soinside.com 2019 - 2024. All rights reserved.