2017-08-09 91 views
0

我已經得到了關於這些兩個選項呈現行爲問題:陣營的setState呈現行爲

export function saveOrCancelStepContentComponents(stepIndex, targetArray, newArray) { 
    // Option 1 
    let stepsData = this.state.stepsData.slice(); 
    stepsData[stepIndex][targetArray] = newArray; 

    this.setState({stepsData: stepsData},() => { 
     console.log("saveStepConditions[]:", this.state.stepsData[stepIndex][targetArray]); 
    }); 

    // Option 2 
    this.setState((prevState) => ({ 
     stepsData: prevState.stepsData.map((currentStep, i) => { 
      if (i === stepIndex) { 
       return { 
        ...currentStep, 
        [targetArray]: newArray, 
       } 
      } 
      return currentStep 
     }) 
    }),() => { 
     console.log("saveStepConditions[]:", this.state.stepsData[stepIndex][targetArray]); 
    }); 
} 

取消和保存有兩個選項,這是說,console.logs是精品。但是,只有選項2纔會重新呈現頁面。選擇1將不會導致任何表型變化。 任何想法,爲什麼?謝謝!

回答

2

此行stepsData[stepIndex][targetArray] = newArray;變異爲stepsData[stepIndex]對象而不是創建一個新對象。

應該是這樣

stepsData[stepIndex] = { 
    ...stepsData[stepIndex], 
    [targetArray]: newArray 
} 

你的地圖功能裏面也做了同樣的方式。

+0

謝謝你,男人! – Nocebo

+0

所以如果我想拼接一個元素,我會做同樣的事情嗎? 'stepsData [stepIndex] .contentComponents = { ... stepsData [stepIndex], contentComponents:stepsData [stepIndex] .contentComponents.splice(I,1) };' – Nocebo

+1

@Nocebo忘掉'splice'。它會改變原始數組並返回拼接的元素。使用'filter'代替。 –