简体   繁体   English

如何使用 React 或 React Native 更新 object 并使用新的 object 值设置 state

[英]How to update an object and set the state with new object values using React or React Native

I am trying to update an object which is stored in my useState hook 'items'.我正在尝试更新存储在我的 useState 挂钩“项目”中的 object。 Code block 1 does not work however code block 2 does.代码块 1 不起作用,但代码块 2 起作用。 The only thing I did was put my items in a new variable.我唯一做的就是将我的项目放入一个新变量中。 Can someone explain why code block 1 does not work however code block 2 does work.有人可以解释为什么代码块 1 不起作用但代码块 2 起作用。

Does NOT work不工作

const Users = () => {
  const [items, setItems] = useState('');

  const folder = {
    id: itemId,
    title: text,
    location: itemLocation,
  };

  // get object index
  const objIndex = items.findIndex(obj => obj.location === itemLocation);

  // update object
  items[objIndex] = folder;

  // set state with update
  setItems([...items]);
};

Below works下面的作品

const Users = () => {
  const [items, setItems] = useState('');

  const folder = {
    id: itemId,
    title: text,
    location: itemLocation,
  };

  // put state into variable
  const myItems = [...items]
  // get object index
  const objIndex = items.findIndex(obj => obj.location === itemLocation);

  // update object
  myItems[objIndex] = folder;

  // set state with update
  setItems(myItems);
};
items[objIndex] = folder;

You should never update state directly like this.你永远不应该像这样直接更新 state。 React assumes you always use the "set" functions to update your state, and will not know when to re-render your components if you modify state directly. React 假设你总是使用“set”函数来更新你的 state,并且如果你直接修改 state 将不知道何时重新渲染你的组件。

https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly

  // update object
  items[objIndex] = folder;

I believe this is the problem.我相信这是问题所在。 I actually never tried to change the state itself (I've always assumed it's read-only).实际上,我从未尝试更改 state 本身(我一直认为它是只读的)。

I will test this further later to be sure.稍后我将对此进行进一步测试以确定。 But usually you don't edit the state directly (the state means the items variable).但通常您不会直接编辑 state(state 表示items变量)。 Either you 1) create an items1 such as items1 = {...items } and then setItems(items1[objIndex] = folder) or you follow your approach in the second code snippet.要么您 1) 创建一个items1 ,例如items1 = {...items }然后setItems(items1[objIndex] = folder)要么按照您在第二个代码片段中的方法。

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

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