Javascript 在react和typescript中使用不变性帮助程序更新两级嵌套对象
我有一个名为TourStop的对象数组,它是两层嵌套的。类型如下Javascript 在react和typescript中使用不变性帮助程序更新两级嵌套对象,javascript,reactjs,typescript,react-hooks,immutability,Javascript,Reactjs,Typescript,React Hooks,Immutability,我有一个名为TourStop的对象数组,它是两层嵌套的。类型如下 TourStops = TourStop[] TourStop = { suggestions?: StoreSuggestion[] id: Uuid } StoreSuggestion= { id: Uuid spaceSuggestions: SpaceSuggestion[] } SpaceSuggestion = { id: Uuid title: string } 我的目标是从特定的Tou
TourStops = TourStop[]
TourStop = {
suggestions?: StoreSuggestion[]
id: Uuid
}
StoreSuggestion= {
id: Uuid
spaceSuggestions: SpaceSuggestion[]
}
SpaceSuggestion = {
id: Uuid
title: string
}
我的目标是从特定的TourStop
我已经编写了以下代码(使用不变性助手和挂钩)
push
操作正常工作。但是,由于某些原因,splice
操作不起作用。我做错了什么
const [tourStopsArray, setTourStopsArray] = useState(tourStops)
// function to remove the store suggestion
const removeSuggestionFromTourStop = (index: number, tourStopId: Uuid) => {
// find the particular tourStop
const targetTourStop = tourStopsArray.find(arr => arr.id === tourStopId)
// Update the storeSuggestion in that tourstop
const filteredStoreSuggestion = targetTourStop?.suggestions?.filter(sugg => sugg.id !== index)
if (targetTourStop) {
// create a new TourStop with the updated storeSuggestion
const updatedTargetTourStop: TourStopType = {
...targetTourStop,
suggestions: filteredStoreSuggestion,
}
const targetIndex = tourStopsArray.findIndex(
tourStop => tourStop.id == updatedTargetTourStop.id,
)
// Find it by index and remove it
setTourStopsArray(
update(tourStopsArray, {
$splice: [[targetIndex, 1]],
}),
)
// add the new TourStop
setTourStopsArray(
update(tourStopsArray, {
$push: [updatedTargetTourStop],
}),
)
}
}