我收到錯誤 [型別轉換運算式應該用括號括起來] 不知道如何更新 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>
uj5u.com熱心網友回復:
您使用的方法稱為擴展運算子...value。在這種情況下,它將原始狀態中的所有專案放入一個新陣列中。
使用擴展運算子創建陣列的副本。這可以防止突變到原始狀態。然后訪問要更新的陣列中的索引并回傳復制和更新的狀態。
if (responseJson.success) {
setResultList(resultList => {
const copy = [...resultList]
copy[indexChange].dataList = response.data
return copy
}
}
或者,您可以使用該.map方法回圈狀態并根據索引回傳更新的物件。
if (responseJson.success) {
setResultList(resultList => resultList.map((item, index) =>
index === indexChange ? ({
...item,
dataList: responseJson.data
}) : item
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411659.html
標籤:
下一篇:模態不會消失
