2017-10-17 58 views
0

在Javascript中的狀態,string, integer and boolean values are immutable, but objects and arrays are mutable.陣營:如何更新既具有可變和不可變值

我們應該如何更新狀態的反應,如果國家有兩種類型的值嗎?

例如

constructor(props) { 
    super(props); 
    this.state = { 
     success: false, 
     error: false, 
     errorMessages: {} 
    }; 
} 

假設你需要upgdate一次全部屬性(successerrorerrorMessages)的,這將是實現這一目標最好的方式?

至少我確定errorMessages不應該直接更新,因爲它本質上是可變的,但其他人呢?

我嘗試了類似下面的內容,但是這樣做的結果是錯誤的。

const errorMessages = { 
    ...this.state, 
    "errorMessages": error.response.data, 
}; 

this.setState({ 
    errorMessages, 
    success: false, 
    error: true, 
}); 

//The errorMessages property will have "success" and "error" property in it 
+0

價值是可變的或不可變的沒有任何關係的陣營與狀態有關。 –

回答

3

只要你errorMessages提供新價值,將作出反應正確更新的狀態。你不是突變狀態直接在這裏,你只是在現場提供新價值,並作出反應會做必要的突變:

this.setState({ 
    errorMessages: error.response.data 
    success: false, 
    error: true, 
}); 
3

所以假設你的狀態是原來這

this.state = { 
    success: false, 
    error: false, 
    errorMessages: {} 
}; 

然後創建一個新的對象爲您errorMessages這樣

const errorMessages = { 
    ...this.state, 
    "errorMessages": error.response.data, 
}; 

this.setState({ 
    errorMessages, 
    success: false, 
    error: true, 
}); 

然後,你的下一個國家會有點這個樣子,而且我不確定這是否是你想要什麼

{ 
    errorMesages: { 
    success: false, 
    error: true, 
    errorMessages: { 
     // content of the error.response.data 
    } 
    }, 
    success: false, 
    error: true 
} 

你可能想直接分配新的狀態,這實際上是你創建的errorMessages常量,你只是在做這件事;)

之所以會這樣,是因爲添加時一個對象的變量沒有值,而只是通過名稱,javascript中會自動命名標籤一樣的變量,例如:

const a = 10; 
 
const b = { 
 
    a 
 
}; 
 

 
// result in: { a: 10 }; 
 
console.log(b);

0

有3種方法來更新狀態:

this.setState({ 
    success: !this.state.success, 
    error: !this.state.error, 
    errorMessages: delete this.state.id // if id were a prop in errorMessages 
}) 

this.setState((prevState) => { 
    return { 
    success: !prevState.success, 
    error: !prevState.error, 
    errorMessages 
    } 
}); 

this.setState((prevState) => { 
    return { 
    success: !prevState.success, 
    error: !prevState.error, 
    errorMessages 
    } 
},() => { // some callback function to execute after setState completes }) 
+0

我應該說明,你應該使用mutators來代替。因此,不應直接從狀態刪除道具,而應將該對象複製到變量中,然後刪除道具,然後將setState設置爲複製的對象。雖然不是一個非常有效的方法。 – stevelacerda7