【问题标题】:(REACT) How to set the value of a state as an object which has attributes which are also objects?(反应)如何将状态的值设置为具有对象的属性的对象?
【发布时间】:2021-04-30 15:12:50
【问题描述】:

我想接收一些输入字段的值并将它们设置为newValue状态,​​但是状态的一些属性是对象本身。我希望 newValue 状态的格式为:

{
        name : {
            firstName : 'Eithan',
            lastName :'Auralius'
        },
        rank : 7
}

现在,对象正在被保存,如下所示:

{
    name.firstName : 'Eithan',
    name.lastName : 'Auralius',
    rank : 7
}

有没有办法通过调整 getValue 函数或输入字段来实现这一点?

//State to store the created or updated user string
const [newValue, setNewValue] = useState();

//onChange triggered function to update 
const getValue = (event)=> {
    
    //Setting the value of the state using the changed input fields
    setNewValue((newValue)=> {
        return {
            ...newValue,
            [event.target.name] : event.target.value,
        }
    });
}

const submitData = (event)=> {
    event.preventDefault();
    console.log(newValue);
}

return (
    <div className='loginRegister'>
        <form onSubmit={submitData}>
            <div className='descriptionInput'><div className='description'>First Name</div>
            {//the name prop is used to set the field name in the getValue function}
            <input type="text" name='name.firstName' defaultValue={member.name.firstName} onChange={getValue}></input></div>
            <button>Submit</button>
        </form>
    </div>
);

【问题讨论】:

  • 你好,我认为你的问题是嵌套数组的设置值。

标签: javascript html reactjs


【解决方案1】:

你可以试试这个。

import { useState } from "react";

export default function App() {
  let defaultState = {
    name: {
      firstName: "",
      lastName: ""
    },
    rank: 0
  };
  const [newValue, setNewValue] = useState(defaultState);

  const submitData = (event) => {
    event.preventDefault();
    console.log(newValue);
  };
  //onChange triggered function to update
  const getValue = (event) => {
    //Setting the value of the state using the changed input fields
    setNewValue((newValue) => {
      return {
        name: {...newValue.name, [event.target.name]: event.target.value},
        rank: newValue.rank
      };
    });
  };

  return (
    <div>
      <form onSubmit={submitData}>
        <div>
          <div>First Name</div>
          <input
            type="text"
            name="firstName"
            defaultValue={newValue.name.firstName}
            onChange={getValue}
          ></input>
        </div>
        <button>Submit</button>
      </form>
    </div>
  );
}

【讨论】:

  • 感谢您的回复,但我有多个此类属性,例如“名称”,它们是对象。不得不寻求更丑陋的解决方案:if(elementName.includes('.')) { const part = elementName.split('.'); result[part[0]][part[1]] = elementValue; }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2019-01-19
  • 2020-09-10
  • 1970-01-01
  • 2019-01-10
  • 2020-01-06
  • 2021-07-19
相关资源
最近更新 更多