this.state = {
abc1,
abc2,
abc3
}
少數國家,爲什麼我不能動態SETSTATE?像
handleDiscount = (count) => {
this.setState({
`abc${count}`: `!this.state.abc${count}`
});
}
當計數爲1/2/3
this.state = {
abc1,
abc2,
abc3
}
少數國家,爲什麼我不能動態SETSTATE?像
handleDiscount = (count) => {
this.setState({
`abc${count}`: `!this.state.abc${count}`
});
}
當計數爲1/2/3
那不是你如何動態地設置對象的屬性。這是模板文字。
handleDiscount = (count) => {
this.setState({
abc[count]: !this.state.abc[count]
});
}
但你不能做到這一點與數組索引反正
的問題是,你正在使用的對象財產申報模板串;這是一個語法錯誤。即便如此,你不能在模板字符串設定爲一個變量和使用,無論是:
let count = 2;
let bar = `baz${count}`;
// This will set foo.bar, not foo.baz2
let foo = {
bar: count
};
你可以做的是使用ES6 computed property names:
let count = 2;
let bar = `baz${count}`;
// This will set foo[<value of bar>], i.e. foo.baz2
let foo = {
[bar]: count
};
而且這還與模板字符串:
let count = 2;
// This will set foo[<template string evaluated>], i.e. foo.baz2
let foo = {
[`baz${count}`]: count
};
此外,您的值中的模板字符串是錯誤的。這不會評估this.state
中的房產,而是它的字符串,例如"!this.state.abc2"
。 !this.state
是代碼,而不是字符串。你需要這個:
!this.state[`abc${count}`]
話雖這麼說,只要設定陣營基於以前的狀態的狀態,你應該調用的setState用函數來代替,從React docs on setState:
[...]如果下一狀態依賴於以前的狀態,我們建議 使用更新函數形式,而不是:
this.setState((prevState) => { return {counter: prevState.quantity + 1}; });
所以,SUMM ARIZE,這應該做的伎倆:
handleDiscount = (count) => {
this.setState((prevState) => {
return { [`abc${count}`]: !prevState[`abc${count}`] }
});
};
爲了獲得目標對象的屬性,請使用target["string property name"]
bracket syntax。
至於添加動態屬性的對象,你應該使用{ ["string property name"]: value }
computed property name syntax。
你的固定代碼應該是這樣的:
handleDiscount = (count) => {
this.setState({
[`abc${count}`]: !this.state[`abc${count}`]
});
}
abc [count] = abc.1 where 1 == count。 – Ved