单击按钮时,过滤器不会删除数组中的每个项目。请协助

The filter is not deleting each item in array while clicking on button. please assist

单击按钮时过滤器不会删除数组中的每一项。来自 onclick 事件的 id 被正确接收。第一个元素也被删除然后它不删除另一个元素。

import React,{useState} from 'react'
    export default function Tour() {
        const tourPack=[
            {
                id:1,
                name:'a'           
            },
            {
                id:2,
                name:'k'
            },
            {
                id:3,
                name:'b'
            }
        ]
         const [TourPackage, setTourPackage] = useState(tourPack)
         const removeTour=(id)=>{//filtering functoin           
        const newTour=tourPack.filter((tour)=>tour.id!==id)
        console.log(newTour);
        setTourPackage(newTour)          
    }
        return (
            <div>
                <h1>{TourPackage.map((t)=>
                    <h1 key={t.id} >{t.name}<button onClick={()=>{removeTour(t.id)}}>Not interested!</button></h1>
                )}</h1>                   
            </div>
        )
    }

您遇到这个问题的原因可能是,当您只需要一个时,您有两个单独的变量指向数组。 tourPack 将在每个渲染周期设置为默认值。 tourPackage 也是如此,因为它基于此。

import React,{useState} from 'react'
    export default function Tour() {
        
         const [TourPackage, setTourPackage] = useState([
            {
                id:1,
                name:'a'           
            },
            {
                id:2,
                name:'k'
            },
            {
                id:3,
                name:'b'
            }
        ]);
         const removeTour=(id)=>{//filtering functoin           
        const newTour=TourPackage.filter((tour)=>tour.id!==id)
        console.log(newTour);
        setTourPackage(newTour)          
    }
        return (
            <div>
                <h1>{TourPackage.map((t)=>
                    <h1 key={t.id} >{t.name}<button onClick={()=>{removeTour(t.id)}}>Not interested!</button></h1>
                )}</h1>                   
            </div>
        )
    }


仅使用 TourPackage