[英]How to update the nested array using useState Hook in React
我收到錯誤 [類型轉換表達式應該用括號括起來]不知道如何更新 useState 中的嵌套數組。
let tempArray = [
{
filterType: "Company",
dataList: []
},
{
filterType: "Vehicle",
dataList: ["Car", "Bike"]
}
]
const [resultList, setResultList] = useState(tempArray)
const [indexChange, setIndexChange] = useState(0)
// Assume here I am using fetch request and getting the response.
if (responseJson.success) {
setResultList(
[
...resultList,
resultList[indexChange].dataList: responseJson.data
]
)
}
在這里,我正在渲染我的結果數組。 單擊列表時,基於索引。 變化反映。
<div className='filterTypeContainer' style={{ backgroundColor: "#F5F6F8", padding: "20px 20px", fontSize: 14, width: "40%" }}>
{ resultList.map((list, index) => {
return <div className='filerType' onClick={()=> setIndexChange(index)}>
<p>{list.filterType}</p>
</div>
}) }
</div>
下面的代碼片段看起來很可疑:
setResultList(
[
...resultList,
resultList[indexChange].dataList: responseJson.data
]
)
在對象的情況下,我們可以解構然后添加更新的鍵值對來獲得優先權。 對於數組項,我懷疑我們是否能夠通過解構來更新特定“索引”處的項。
我可以知道是否可以試用以下代碼段:
if (responseJson.success) {
const rl = [...resultList];
rl[indexChange].datalist = responseJson.data
setResultList(rl);
}
您使用的方法稱為擴展運算符...value
。 在這種情況下,它將原始 state 中的所有項目放入一個新數組中。
使用擴展運算符創建數組的副本。 這可以防止對原始 state 的突變。 然后訪問要更新的數組中的索引並返回復制和更新的 state。
if (responseJson.success) {
setResultList(resultList => {
const copy = [...resultList]
copy[indexChange].dataList = response.data
return copy
}
}
或者,您可以使用.map
方法循環遍歷 state 並根據索引返回更新的 object。
if (responseJson.success) {
setResultList(resultList => resultList.map((item, index) =>
index === indexChange ? ({
...item,
dataList: responseJson.data
}) : item
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.