从阵列中删除项目反应挂钩无法正常工作

Remove item from array react hooks not working properly

从数组中删除项目仅对最后呈现的项目起作用,但选择的项目已从列表中删除

  const [otherPhones, setOtherPhones] = useState([]);

    {otherPhones.map((item, i) => {
      return (
        <View
          style={{
            ...DefaultStyles.iconContainer,
            marginBottom: hp("1.25%")
          }}
          key={i}
        >
          <PhoneNumberPicker
            placeholder={i18n.t("other_phone")}
            style={{ flex: 10 }}
            countryHint={countryHint}
            onChange={value => {
              _handleOtherPhone(value, i);
            }}
          />
          <IconButton
            style={{ flex: 1 }}
            icon="trash-can-outline"
            color={SECONDARY}
            size={SCALE_20}
            onPress={_deleteOtherPhone.bind(this, i)}
          />
        </View>
      );
    })}

  const _deleteOtherPhone = index => {
    const temp = [...otherPhones];
    temp.splice(index, 1);
    setOtherPhones(temp);
  };

当我删除 PhoneNumberPicker 并仅显示简单的 属性 项目时,一切正常。 PhoneNumberPicker 它是一个带有一些附加组件的 TextInput。

也许这会对某人有所帮助,我使用 useRef() 反应挂钩来引用 DOM 上的每个渲染子对象,然后我使用新索引更新它们(删除选定元素后)项目。

父元素:

 const elRefs = useRef([]);
 if (elRefs.current.length !== otherPhones.length) {
    // add or remove refs
    elRefs.current = Array(otherPhones.length)
      .fill()
      .map((_, i) => elRefs.current[i] || createRef());
  }

...

  const _deleteOtherPhone = index => {
  const temp = [...otherPhones];
  temp.splice(index, 1);
  for (let i = 0; i < temp.length; i++) {
      const element = temp[i];
      elRefs.current[i].current.removeItem(element);
  }
...
}

...
    <PhoneNumberPicker
    placeholder={i18n.t("other_phone")}
    style={{ flex: 10 }}
    ref={elRefs.current[i]}
    countryHint={countryHint}
    onChange={value => {
    _handleOtherPhone(value, i);
     }}
   />
...

子元素电话号码选择器: 更新 phone 个号码:

  removeItem(item) {
    this.setState({ phoneNo: item.phoneNumber });
  }