首页 > 解决方案 > React Hook List 大小 - React Native

问题描述

我目前正在研究钩子,我正在尝试在单击按钮时创建一个句子,并验证它们是否正确。但是,要做到这一点,我的列表最多只能有 5 个字,我很难这样做。

这个想法是,当列表达到 5 个值时,它具有最大大小。当添加另一个值时,它会弹出第一个值(索引 0)并添加最后一个值。

这是我的代码:

  const [sentence, setSentence] = useState([]);

  if(sentence==='HelloYouAreMyFriend'){
    console.log('sentence')
  }

        </View>
  <View> 
  {selectedWord.word.map(word => (
    <TouchableOpacity key={word}
onPress={() => setCount(sentence + word )}

  }>

Example 
        // 1 button click: Hello
        // 2 button click: HelloYou
        // 3 button click: HelloYouAre
        // 4 button click: HelloYourAreMy
        // 5 button click: HelloYourAreMyFriend
        // 6 button click: YourAreMyFriendJosh 
        Need SIZE max ==> 5 words in the list

标签: reactjsreact-nativereact-hooks

解决方案


我假设您正在处理handlePlaySound功能中的所有内容。

const[sentence, setSentence] = useState([]);

const handlePlaySound = (event) => {
const word = event.target.key
const localSentence = [...sentence]; //because you never mutate the state
  if (localSentence.length < 5) {
    setSentence([...localSentence], word)
  } else { 
    localSentence.splice(0,1);
    setSentence([...localSentence], word);
  }
}

并且从组件中您应该在事件中传递单词

<TouchableOpacity key={word} onPress={handlePlaySound} />

推荐阅读