无法获取数组 React JS 中元素的索引

unable to get the index of element in array react js

提问人:user1450966 提问时间:11/7/2023 更新时间:11/7/2023 访问量:26

问:

  const editAddHandler = (event, key) => {
    const db = getDatabase();
    onValue(ref(db, `users/${userId}/addressData`), (snapshot) => {
      const addresslist = [];
      snapshot.forEach((childSnapshot) => {
        const keyName = childSnapshot.key;
        const data = childSnapshot.val();
        addresslist.push({ key: keyName, data: data });
      });
      props.setSavedAddress(addresslist);
    });

    console.log("array of element",props.savedAddress)

    const clickedAddress = props.savedAddress.findIndex(element => element === key)
    console.log("clicked key",clickedAddress)
        
    const keyValue = props.savedAddress[key];
    console.log("keyvalue",keyValue)
    
    console.log("key",key)

    if(key === props.savedAddress[key]) {
      setValues({
        name: props.savedAddress[key].data.name,
        phone: props.savedAddress.phone,
        pincode: props.savedAddress.pincode,
        address: props.savedAddress.address,
        city: props.savedAddress.city,
        state: props.savedAddress.state,
        landmark: props.savedAddress.landmark,
        defaultAdd: props.savedAddress.defaultAdd,
      })
    }
    props.showAddressHandler();
  };

enter image description here

无法获取 props.savedAddress 列表的索引,需要比较 index 和 key onClick 事件。
Lorem Ipsum 只是印刷和排版行业的虚拟文本。自 1500 年代以来,Lorem Ipsum 一直是行业标准虚拟文本,

reactjs 数组 react-hooks find

评论

0赞 Damian Busz 11/7/2023
键是一个字符串,props.savedAddress 是具有键属性的对象数组,请尝试const clickedAddressIndex = addresslist.findIndex(element => element.key === key);
0赞 derpirscher 11/7/2023
您的包含对象。比较对象具有非常具体的规则,即当且仅当它是完全相同的对象(即指向内存中的相同位置)时,它才会返回 true。此外,似乎也不太有用......addresslist===if(key === props.savedAddress[key])

答:

0赞 user1450966 11/7/2023 #1

const clickedAddress = props.savedAddress.findIndex((element,i) => i === 键)

这将给出索引