📜  如何在 React Hooks 的状态对象中设置对象键?

📅  最后修改于: 2022-05-13 01:58:10.163000             🧑  作者: Mango

如何在 React Hooks 的状态对象中设置对象键?

我们可以使用以下方法更新具有嵌套对象的 React hooks 状态对象,该对象包含具有索引键的对象,在此之前,请考虑以下示例:

示例:以下是 默认状态对象:

const [data, setData] = useState({
   name:'',
   contact:'',
   address:{
     0:{},
     1:{},
   }
})

以下是更新嵌套对象后所需的输出:

{
  name:'',
  contact:'',
  address:{
    0:{"city":'jaipur'},
    1:{},
  }  
}

解决方案:我们可以使用以下语法在状态对象中设置对象键:

data.address[0].city = 'jaipur';
setData({...data});

创建反应应用程序:

第 1 步:使用以下命令创建一个 React 应用程序:

npx create-react-app foldername

第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移动到该文件夹:

cd foldername

文件名:App.js

Javascript
import React, { Component, useState } from "react";
  
const App = () => {
  const [data, setData] = useState({
    name: '',
    contact: '',
    address: {
      0: {},
      1: {},
    }
  })
  
  const handleUpdate = () => {
    data.address[0].city = 'jaipur';
    setData({ ...data });
  }
  
  return (
    
             { data.address[0].city + " "}     
  ); }    export default App;


运行应用程序的步骤:从项目的根目录使用以下命令运行应用程序:

npm start

输出:

  • 以下将是单击按钮之前的输出:

    点击前

  • 点击按钮后的输出如下:

    点击后