简体   繁体   English

使用钩子更新反应组件中的 object 值

[英]Update object value in react component using hooks

Basically the prompt is this.基本上提示是这样的。 You are given a list of users and their salaries.您将获得一份用户列表和他们的薪水。 When you click on the salaries an input field should appear so you can update the user salary.当您单击薪水时,应出现一个输入字段,以便您可以更新用户薪水。 the input field should not show at the same time as the hard coded salary.输入字段不应与硬编码工资同时显示。 Basically all of the functionality i need is there other than the input field not actually updating the salary.基本上我需要的所有功能都存在,除了输入字段实际上并没有更新薪水。 extra credit would be when i click on a salary only the input field for that salary showing up but thats not the issue I am currently trying to fix.额外的积分是当我点击薪水时,只会显示该薪水的输入字段,但这不是我目前正在尝试解决的问题。 I can see based on console.logs that the line user.salary = salaryInput is essentially where the code stops working so any help would be great.我可以根据 console.logs 看到行 user.salary = SalaryInput 基本上是代码停止工作的地方,所以任何帮助都会很棒。

import { useState, } from 'react';

const users = [
  { name: "John Doe", id: 1, salary: 111111 },
  { name: "Jane Doe", id: 2, salary: 2222222 },
  { name: "Billy Doe", id: 3, salary: 3333333 }
];

const Salary = () => {
  
  const [displayUser, setDisplayUser] = useState(users);
  console.log('displayUser:', displayUser)
  const [salaryInput, setSalaryInput] = useState(); // [value, setvalue
  const [edit, setEdit] = useState(false)

  const onSalaryChange = (event) => {
    const salaryFieldString = event.target.value;
    setSalaryInput(salaryFieldString); 
    //console.log(salaryInput)
  }

  const onClickHandler = (event) => {
    const { id } = event.target;
    const updatedUser =  users.map((user) => {
      //console.log('id:', id)
      //console.log('user.id:', user.id)
      if (user.id === id) 
        user.salary = salaryInput;
        //console.log('salaryInput:', salaryInput)
        //console.log('user.salary:', user.salary)
        //console.log('user:', user)
        return user;
    })
    console.log('updateduser:', updatedUser)
    setDisplayUser(updatedUser)
    setEdit(false);
  }

  return (
    <div>
      {displayUser.map((user) => {
        return (<div key={user.id}>
                <div>{user.name}</div>
                <div onClick={() => {setEdit(true)}}>
                {!edit && <div>{user.salary}</div>}
                {edit && <input type='number' onChange={onSalaryChange}></input>}
              </div>
            <button onClick={onClickHandler} id={user.id}>update Salary</button>
          </div>
        )}
      )}
    </div>
  )
}

export default Salary

Try returning尝试返回

{...user, salary: salaryInput}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM