【问题标题】:How to update the nested array using useState Hook in React如何在 React 中使用 useState Hook 更新嵌套数组
【发布时间】:2022-01-15 18:16:05
【问题描述】:

我收到错误 [类型转换表达式应该用括号括起来] 不知道如何更新 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>

【问题讨论】:

  • 数组中的表达式resultList[indexChange].dataList : responseJson.data是什么意思?
  • 这里我试图根据最初为 0 的 (indexChange) 更新结果数组。但是遇到错误不知道如何在javascript中使用解构概念更新嵌套数组。
  • 是的,但是该行应该做什么?我不认为解构是问题,而是那一行...
  • 假设您有一个不同过滤器的列表,当您单击一个基于通过获取请求或临时错误更新的 resultList 的过滤器时。

标签: javascript arrays reactjs use-state array-map


【解决方案1】:

您使用的方法称为扩展运算符...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
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 2021-04-28
    • 2020-09-22
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多