在react和Typescript中使用不可变帮助器更新两级嵌套对象

时间:2019-11-28 09:47:35

标签: javascript reactjs typescript react-hooks immutability

我有一个称为TourStop的对象数组,该对象是两层嵌套的。类型如下。

TourStops = TourStop[]

 TourStop = {
  suggestions?: StoreSuggestion[]
  id: Uuid
}
 StoreSuggestion= {
  id: Uuid
  spaceSuggestions: SpaceSuggestion[]
}

SpaceSuggestion = {
 id: Uuid
 title: string
}

我的目标是从特定的StoreSuggestion中移除特定的TourStop 我编写了以下代码(使用不可变性帮助器和挂钩)

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],
        }),
      )
    }
  }

push操作正确运行。但是,由于某些原因,splice操作不起作用。我在做什么错了?

0 个答案:

没有答案