Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/406.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在react和typescript中使用不变性帮助程序更新两级嵌套对象_Javascript_Reactjs_Typescript_React Hooks_Immutability - Fatal编程技术网

Javascript 在react和typescript中使用不变性帮助程序更新两级嵌套对象

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

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

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