【问题标题】:Map Data into another array using Hooks使用 Hooks 将数据映射到另一个数组
【发布时间】:2021-08-30 16:35:14
【问题描述】:

所以我有大量不需要的 Api 数据,我想将这些数据隔离在另一个数组中。

我正在尝试弄清楚如何使用钩子来做到这一点。

Array [
  Object {
    "id": 2976,
    "name": "Device 2",
  },
  Object {
    "id": 2977,
    "name": "Device 1",
  },
 Object {
    "id": 2978,
    "name": "Device 3",
  },
]

我有一个钩子

const [devices, setDevices] = useState([]);

我希望设备以 [Device1, Device2, Device3] 结尾

数组中还有一堆其他数据,但这是为了让您大致了解我只需要一个对象。

【问题讨论】:

    标签: react-native react-hooks jsx


    【解决方案1】:

    您可以使用 Array.map 创建一个新数组,其中仅填充名称(或您想要的任何名称)

    objArray = [{
      "id": 2976,
      "name": "Device 2",
    },{
      "id": 2977,
      "name": "Device 1",
    },{
      "id": 2978,
      "name": "Device 3",
    }];
    
    // create a new array consisting of just the names from the objects
    const arrayOfNames = objArray.map((obj) => obj.name);
    
    setDevices(arrayOfNames);
    

    您可以将 Array.map 视为从输入数组创建一个新数组,其中每个项目都根据右侧的公式进行替换。

    numbers = [1, 2, 3];
    
    numbers.map((x) => x)     // returns [1, 2, 3]
    numbers.map((x) => x + 1) // returns [2, 3, 4]
    numbers.map((x) => 0)     // returns [0, 0, 0]
    

    【讨论】:

    • 是的,我可以理解这一点,但是有没有办法可以将其设置为钩子状态?
    • setDevices(arrayOfNames) 这样做不是吗?或者你的意思是你想把所有这些逻辑放到一个钩子里?
    猜你喜欢
    • 2015-07-14
    • 2017-05-26
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多