[英]How to setState of an object inside an array in parent component from child component?
[英]How to select a specific object from array inside setState?
class Example extends React.Component{ constructor(props){ super(props); this.state = { array: [{n: 0}, {n: 1}, {n: 2}] } } selectObjectFromArray = index => { this.setState({ array: //??? }) }
我們只知道索引,我們要在數組中編輯對象。 我們不能像this.state.array[1] = ...
,也不能像setState({array[1]:...
我被認為是關於傳播的: array: [...this.state.array,
但是在這種情況下,我們無法設置要編輯的位置,那么在這種情況下我們該怎么辦?
要更新狀態數組,您必須創建它的副本,更新一些條目,然后將新數組推回該狀態。
這是一個簡單的示例,其中的按鈕更新了最后一項:
import React from "react";
import ReactDOM from "react-dom";
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
array: [{ n: 0 }, { n: 1 }, { n: 2 }]
}
}
render() {
return <div>
<ul> {
this.state.array.map((item,key) => {
return <li key={key} >{item.n} </li>
})
}
</ul>
<button onClick={this.updateLast}>update first</button>
</div>
}
updateLast = () => {
this.selectObjectFromArray(this.state.array.length -1 )
}
selectObjectFromArray = index => {
// create a copy of the array
let newArr = this.state.array;
// the item variable is optional but hope clarifies how this works
let item = newArr[index];
item = {
n: item.n * 2
}
newArr[index] = item;
// update the state with the new data
this.setState({
array: newArr
})
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);
也可以在以下位置找到該工作示例: https : //codesandbox.io/s/o4x6mpnozq
我們只知道索引,我們要在數組中編輯對象
給定一個knownIndex
this.setState({
array:
[ ...this.state.array.slice (0, knownIndex) // <-- items up to the index
, someUpdate(this.state.array[knownIndex])) // <-- updated object
, ...this.state.array.slice (knownIndex + 1) // <-- items after the index
]
})
您可以執行的另一種方法是使用Array .map
函數。 我們也將其設為通用函數
const updateAtIndex = (xs, i, f) =>
xs .map ((x, j) => i === j ? f (x) : x)
在組件中,您可以像這樣使用它
this.setState ({
array: updateAtIndex (this.state.array, knownIndex, f)
})
其中f
是用於更新對象的某些函數,例如
// returns a new object with the n property doubled
const f = obj =>
({ n: obj.n * 2 })
在編寫泛型函數時,我希望使它們更健壯。 如果您在程序中使用此技術,建議對上述功能進行一些更改。 這些更改可以更有效地傳達參數類型,並使讀者可以更好地推斷函數的返回類型。
const identity = x =>
x
const updateAtIndex = (xs = [], i = 0, f = identity) =>
xs .map ((x, j) => i === j ? f (x) : x)
const f = ({ n = 0 }) =>
({ n: n * 2 })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.