【问题标题】:Remove item from array react hooks not working properly从数组反应钩子中删除项目无法正常工作
【发布时间】:2020-05-22 19:40:44
【问题描述】:

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

  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。

【问题讨论】:

  • 用过滤器代替拼接怎么样?你试过了吗?
  • 是的,我也尝试过,在这两种情况下,元素都从数组中删除,但子组件未正确更新。顺便感谢您的回复。

标签: javascript react-native react-hooks rendering


【解决方案1】:

也许这会对某人有所帮助,我使用 useRef() react hooks 来引用 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);
     }}
   />
...

子元素 PhoneNumberPicker : 更新电话号码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-12-17
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多