【问题标题】:How to update an array of object inside another object in React如何在 React 中更新另一个对象内的对象数组
【发布时间】:2023-01-20 03:22:47
【问题描述】:

我正在尝试更新用户对象中的单个键/值对,该对象包含另一个名为“教育”的对象数组。我在列表组件上设置了一个名为“index”的自定义属性,以便在更新时访问数组索引。

// User object
const [userData, setUserData]  = useState({
    firstName: '',
    lastName: '',
    title: '',
    email: '',
    phoneNumber: '',
    website: '',
    bio: '',
    education: [
      {
        id: uniqid(),
        school: '',
        degree: '',
        city: '',
        state: '',
        timeframe: ''

      }
    ]
})
// Render input form for Education
const listItems = props.userData.education.map((user, index) => {
    return (
      <div key={index}>
        <h2>University/School #{index}</h2>
        <input
          type="text"
          index={index}
          placeholder="Your school"
          name="school"
          onChange={props.handleChange}
          value={props.userData.education[index].school}
        />
      </div>
    );
  });

为 onChange 创建了这个函数处理程序,但它只返回一个空字符串并且不更新对象。我觉得我在这里错误地使用了传播运算符,但无法弄清楚如何正确地将它们组合在一起。

// Update user education state
const handleChange = (e) => {
  const { value, name } = e.target
  const index = e.target.getAttribute('index')
  setUserData(prevUser => ({
    ...prevUser,
    [prevUser.education[index]]: {
      [name]: value
    }
  }))
}

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    您不需要添加自定义索引值并将其从属性中获取。您可以将其添加到更改回调中:

    const listItems = props.userData.education.map((user, index) => {
        return (
          <div key={index}>
            <h2>University/School #{index}</h2>
            <input
              type="text"
              index={index}
              placeholder="Your school"
              name="school"
              onChange={(e) => props.handleChange(e, index)}
              value={props.userData.education[index].school}
            />
          </div>
        );
      });
    

    如果你在你的handleChange中运行console.log,你会看到valuename是什么?

    我希望您能学到一些有关如何调试代码的知识。

    const handleChange = (e, index) => {
    
      const { value, name } = e.target
      console.log({value});
      console.log({name});
    
      setUserData(prevUser => {
        const newItem = {
           [prevUser.education[index]]: {
              [name]: value
           }
        }
        console.log({newItem}); // is this what you expect?
    
        return ({
        ...prevUser,
        ...newItem,
        
      })))
    }
    

    最后,你的value应该直接来自state,而不是Props。我假设您的状态与您的渲染位于同一组件内?否则,您是否将状态作为道具传递给您的消费组件?

    至于你的传播,是的,你错过了一点。

    const newItem = {
           [prevUser.education[index]]: {
             ...[prevUser.education[index]], // without this you will overwrite all the previous data
              [name]: value
           }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      相关资源
      最近更新 更多