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

Item in array deleted but UI not update in React Native

本应用由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>
  )
}

我会创建新对象而不是操纵现有对象。

const onPressDeleteWordButton = (index) => {

        if(wordsetObject.words.length) {
          setWordsetObj(modifiedObj => {
            return {
              ...modifiedObj,
              words: modifiedObj.words.filter((pr, ind) => ind !== index)
            }
          });
        }
    }