Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - 在react和Typescript中使用不可变帮助器更新两级嵌套对象(Updating a two level nested object using immutability-helper in react and typescript)

I have an array of object called TourStop, which is two level nested.

(我有一个称为TourStop的对象数组,该对象是两层嵌套的。)

The types are as below.

(类型如下。)

TourStops = TourStop[]

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

SpaceSuggestion = {
 id: Uuid
 title: string
}

My goal is to remove a particular StoreSuggestion from a particular TourStop I have written the following code(uses immutability-helper and hooks)

(我的目标是从特定的TourStop删除特定的StoreSuggestion ,我编写了以下代码(使用immutability-helper和hooks))

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

The push action works correctly.

(push作正常工作。)

However the splice action doesn't work for some reason.

(但是,由于某种原因, splice操作无法正常工作。)

What am I doing wrong?

(我究竟做错了什么?)

  ask by Sooraj Chandran translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...