所以我试图将一个对象分配给一个对象属性 . 我发现轻微的成功,但对象被错误地分配 . 我正在映射数组以显示卡片 .

有大牌和小牌 . 大牌可以分配预定数量和类型的小卡片 . 你可以在一副牌中拥有多张相同的大牌 . 大卡存储在一个数组中

我的大牌有一个对象属性:

upgrades: {
  preterminedSmallCard: null,
  preterminedSmallCard: null
}

点击后,我试图根据阵列中每张Big卡的唯一ID添加一张插入插槽的小卡片 .

它不是将它添加到数组中的单个实例,而是将其添加到具有相同名称的每个大卡中 . 如果它的名称不同,则不会添加它 .

这是我的代码,带有尖锐的评论:

addUpgradeHandler = (card) => {
    //determines which upgrade type to add - console.logging properly
    const upgradeType = this.props.match.params.type;

    //finding the index of targeted ship
    const shipIndex = this.props.shipInfo.findIndex(index => {
        /** 
        * Router passes the id of the targeted ship, the compared against
        * returns true to the targeted ship, false for the ones not targeted
        * ID's generated with npm package uniqID - unique id for each instance in array
        **/
        return (index.id === this.props.match.params.id);
    });

    console.log(shipIndex); //evaluates properly to the target index position

    //mapping the state to a copy
    const newShips = [...this.props.shipInfo];

    //targeting the upgrades property inside of the correct index pos
    const upgrades = newShips[shipIndex].upgrades;

    console.log(upgrades); //returns only one index pos of the state with the upgrade equipped

    const currentPoints = this.props.points;

    //checking if adding the card will bust the max points allowed
    if (currentPoints + card.points < 400) {

        console.log(upgrades[upgradeType]); // returns one object, the value stored in the proper place
        /**
         * Issue starts here
         * - card -> represents object that the map below is, issue persists if object is explicitly written
         * assigns upgrade card object to the correct property type, but for every ship with the same name
         * The name of the ship is not being evaluated anywhere in this function
         **/
        //not intended

        upgrades[upgradeType] = card;
    }      
}

其他奇怪的事情:

  • 我通过拼接使用与上面相同的比较从数组中删除大牌,并且只以所需的方式拼接一个 .

  • 从阵列拼接后,如果我添加一张同名的大牌,即使它有一个全新的ID,也会使用 uniqId() 呈现相同的小卡片 .

所以TL; DR,我用于定位特定索引的技术是正确的控制台日志记录,但是对象的名称分配错误,我在代码中根本没有评估 .