[英]Update state of array nested inside object (ReactJS)
我有一個處於狀態(“汽車”)的對象,該對象具有多個鍵,其中一個是數組(“功能”)。 我正在嘗試做幾件事。
我已經在網上對此進行了相當多的研究,但沒有發現任何內容(可能是因為這是不可能的)。 無論哪種方式,這是我的代碼:
class Car extends React.Component {
state = {
car: {make: 'Toyota', model: 'Camry', features: []},
}
handleChange = (e, index) => {
const value = e.target.value
let features = this.state.car.features.slice() // create mutable copy of array
features = features[index].concat(value)
this.setState({...this.state.car, features: features})
}
handleAddFeature = () => {
let features = this.state.car.features.slice()
features.push('')
this.setState({...this.state.car, features: features})
}
render() {
return (
{
this.state.car.features.map((f, index) => { return <input key={index} onChange={e => this.handleChange(e, index)}>{feature}</input>
}
<button onClick={this.handleAddFeature}>Add Feature</button>
)
}
}
好的,我的工作方式與@Snkendall的答案非常相似。 我的handleChange
函數在下面列出:
handleChange = (e, index,) => {
let array = this.state.car.features.slice() // create mutable copy of the array
array[index] = e.target.value // set the value of the feature at the index in question to e.target.value
const newObj = { ...this.state.car, features: array } // create a new object by spreading in the this.state.car and overriding features with our new array
this.setState({ car: newObj }) // set this.state.car to our new object
}
此解決方案與@Snkendall的區別在於定義了newObj
變量。 事實證明,這是更新嵌套在狀態對象內的單個鍵的唯一方法。
廣告1
handleAddFeature = () => {
const car = this.state.car
car.features.push('Your feature')
this.setState({ car })
}
只需創建副本並推送到汽車功能即可獲得新價值。
廣告。 2創建名為Feature的組件。 他將擁有自己的狀態,您可以在其中修改字符串,並可以通過道具將數據提取到“汽車”中。
有幾件事可能會引起您的問題……如果您的組件具有狀態,則應使用構造函數,並將“ this”引用綁定到其中,以防止“ this”引用全局變量。 您只需像這樣包裝狀態:
class Car extends React.Component {
constructor() {
super()
this.state = {
car: {make: 'Toyota', model: 'Camry', features: []},
}
this.handleChange = this.handleChange.bind(this)
this.handleAddFeature = this.handleAddFeature.bind(this)
}
這是一篇關於'this'的很棒的文章: http : //2ality.com/2017/12/alternate-this.html
可能引起問題的另一個方面是features = features[index].concat(value)
...,因為每次更改(擊鍵)時,都會在狀態上一次又一次地將輸入標簽的值封裝在當前字符串上。 您可以像這樣在數組的該索引處重置元素的值:
handleChange = (e, index) => {
const value = e.target.value
let features = this.state.car.features.slice()
features[index] = value
this.setState({...this.state.car, features})
}
這樣,每次擊鍵都將狀態值重置為反映在輸入中創建的更改。 實際上,您實際上根本不需要使用handleAddFeature,因為狀態已通過handleChange更新。
我正在更改features:features
更改為僅features
因為ES6分解具有這種有趣的features:features
如果某個鍵及其值相同,則只需要引用一次即可,然后計算出來。 這只是保持代碼干燥的一種很酷的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.