数组中的项目已删除,但UI无法在React Native中更新

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

此应用由react-native开发。我知道这个问题可以重复,但是我尝试了所有解决方案,但是它们没有用。

我很困惑。当对象中的某些项目adding / pushing数组时,UI元素将更新。但是,当我在同一数组中delete / splice时,此机制不起作用,UI元素也不会更新。为什么?

function createWordsetObject() {
  const object = {
    name: '',
    words: [],
  }

  return object
}

export default function AddWordScreen({ navigation, route }) {
  const [wordsetObject, setWordsetObj] = useState(
    route.params == null ? createWordsetObject() : route.params.wordSetObject
  )
  const [wordsetName, setWordsetName] = useState(
    route.params == null ? '' : route.params.wordSetObject.name
  )
  const [word, setWord] = useState('')
  const [meaning, setMeaning] = useState('')

  const onPressAddButtonHandler = () => {
    if (word != null && meaning != null) {
      var addRecord = { word: word, meaning: meaning }
      wordsetObject.words.push(addRecord)
      setWord('')
      setMeaning('')
      printLog()
    }
  }
  const onPressDeleteWordButton = index => {
    var modifiedObj = wordsetObject
    if (modifiedObj.words.length > 0) {
      console.log(modifiedObj.words.length)
      modifiedObj.words.splice(index, 1)
    }
    setWordsetObj(modifiedObj)
    console.log(wordsetObject.words.length)
  }

  return (
    <ScrollView>
      {wordsetObject.words.map((item, index) => {
        return (
          <ListItem
            key={index}
            title={item.word}
            subtitle={item.meaning}
            bottomDivider
            rightIcon={
              <View style={{ flexDirection: 'row' }}>
                <MCIcon name="pencil" size={22} />
                <MCIcon
                  name="delete"
                  size={22}
                  color="red"
                  onPress={() => onPressDeleteWordButton(index)}
                />
              </View>
            }
          />
        )
      })}
    </ScrollView>
  )
}

reactjs react-native react-native-elements
1个回答
0
投票

我将创建一个新对象,而不是操纵现有对象。

const onPressDeleteWordButton = (index) => {

        if(wordsetObject.words.length) {
          setWordsetObj(modifiedObj => {
            return {
              ...modifiedObj,
              words: modifiedObj.words.filter((pr, ind) => ind !== index)
            }
          });
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.