简体   繁体   English

更新数组中对象的值

[英]Update object value in array React hooks way

How would I update a title of the specific id with hooks state setup. 如何使用挂钩状态设置来更新特定ID的标题。 Here: 这里:

const NotesContainer = ({

}) => {
  const [notesDummyData, setNotesDummyData] = useState([
    {
      id: '5',
      title: 'Sauna',
    },
    {
      id: '7',
      title: 'Finland',
    },
  ]);

  const onChangeItemName = (newTitle, oldTitle, itemId) => {

    //Update a new title here for id 7

  };

Could not find any example for setState hooks. 找不到setState挂钩的任何示例。

You can use Array.map() . 您可以使用Array.map() For each item check if the id is equal to itemId . 对于每个项目,检查id是否等于itemId If it this, spread the item, and replace the title . 如果是这样,请展开该项目,然后替换title If not, return the original item: 如果不是,请返回原始项目:

const onChangeItemName = (title, itemId) => {
  setNotesDummyData(notesDummyData.map(o => o.id === itemId ? ({
    ...o,
    title
  }) : o));
};

Just map through the items and if the id is equal to the selected id you modify only the value: 只需映射各个项目,如果id等于所选的id,则只需修改值:

 const onChangeItemName = (newTitle, oldTitle, itemId) => {
      setNotesDummyData(notesDummyData.map(x => {
           if(x.id !== itemId) return x
           return {...x, title: newTitle}
      }))
 }

It's easy to update data using React Hook, but there is not working setState() , so there will be working [notThis, thisOne(setNotesDummyDate)] to update your data. 使用React Hook更新数据很容易,但是没有可用的setState() ,因此可以使用[notThis, thisOne(setNotesDummyDate)]来更新数据。

const [notesDummyData, setNotesDummyData] = useState([
    {
      id: '5',
      title: 'Sauna',
    },
    {
      id: '7',
      title: 'Finland',
    },
  ]);

Using React Hook method to Update data: 使用React Hook方法更新数据:

const onChangeItemName = (newTitle, oldTitle, itemId) => {
       setNotesDummyDate = useState([
    {
      id: itemId, // Update
      title: newTitle,
    },
    {
      id: itemId, // Update
      title: newTitle,
    },
  ]);
 }

Still Curious, study here about useState() 仍然很好奇, 在这里学习useState()

Cheer you! 加油!

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

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