簡體   English   中英

數組內對象的reactJs setState更改屬性

[英]reactJs setState change property on object within an array

我有點卡住了。 我嘗試用另一個數組中的另一個對象覆蓋一個數組中的某個對象:

onStepsLayoutChange = (layout) => {
        console.log("The new layout is", layout); //Array
        this.setState((prevState) => ({
            layout: layout,
            stepsData: prevState.stepsData.map(step => {
                layout.map(l => {
                  if(step.identifier === parseInt(l.i)){
                      console.log("Match", l, step); // "l" is not empty and actually matches only if "id" is identical
                      return {
                          ...step,
                          layout: l //I want to override "layout" with the current layout "l"
                      }
                  }
                });
                return step
            })
        }), () => console.log("LayoutChange:", this.state.layout, this.state.stepsData)); // "layout" in each step is empty
    };

在這種情況下我的失敗是什么?

如果stepsData必須是一個數組數組,則會忘記一個返回值:

onStepsLayoutChange = (layout) => {
        console.log("The new layout is", layout); //Array
        this.setState((prevState) => ({
            layout: layout,
            stepsData: prevState.stepsData.map(step => {
                return layout.map(l => { //here <---
                  if(step.identifier === parseInt(l.i)){
                      console.log("Match", l, step); // "l" is not empty and actually matches only if "id" is identical
                      return {
                          ...step,
                          layout: l //I want to override "layout" with the current layout "l"
                      }
                  }
                });
                return step
            })
        }), () => console.log("LayoutChange:", this.state.layout, this.state.stepsData)); // "layout" in each step is empty
    };

問題是,您缺少#array.map的默認行為。 對於每個數組,值映射默認將返回一些undefined值。 您正在map內運行map,因此stepData的最終值將是:

[[...], [...], [....] ....]

而不是使用嵌套映射,請使用#array.findIndex#array.find並返回值。

像這樣寫:

stepsData: prevState.stepsData.map(step => {
    let index;
    index = layout.findIndex(l => step.identifier === parseInt(l.i));

    if(index >= 0){
        return {
            ...step,
            layout: layout[index]
        }
    }

    return step;
})

檢查以下代碼段:

 let a = [1,2,3,4,5]; let b = [2,3]; let result = a.map(i => { return b.map(j => { if(i === j) return 0; }) return i; }) console.log(result); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM