简体   繁体   English

通过 useState 更新 state 后,React 组件未呈现

[英]React component isn't rendering after updating state by useState

I want to update an state object userInfo which contains an array named work which is an array of objects我想更新一个 state object userInfo ,其中包含一个名为work的数组,它是一个对象数组

My Database object userInfo looks like this我的数据库 object userInfo看起来像这样

{
"_id":"61a6a1d64707c03465eae052",
"fullName": "Md Nurul Islam",    
"works": 
[
    {
    "isEditing": false,
    "_id": "61a6a1d64707c03465eae053",
    "company": "Amazon Logistics",
    "position": "Sortation Associate",
    "isCurrent": true
    }, 
    {
        "isEditing": false,
        "_id":"61a6a1d64707c03465eae054",
        "company": "The Rani Indian Takeway",
        "position": "Customer Service Assistant",
        "isCurrent": false,
    }
]    
}

But I don't want update the database, i just want to update the state userInfo in frontend to go editing mood, for this when the user clicks edit next to work section, the properties isEditing will be toggled.但是我不想更新数据库,我只想将前端的 state userInfo更新为 go 编辑心情,为此,当用户单击工作部分旁边的编辑时,属性isEditing将被切换。

Below is my code下面是我的代码

const [userInfo, setUserInfo] = useState(user);
const workToggleHandler = (work) => 
{
  setUserInfo((prev) => {
  prev.works.map((p) => {
    if (p._id === work._id) {
      p.isEditing = !p.isEditing;
    }
    return p;
  });
  return prev;
});

With this code, my state object is updated But my components are not re-rendered使用此代码,我的 state object 被更新但我的组件没有重新渲染

React does not look at the data of the object but rather on the pointer of the object. React 不会查看 object 的数据,而是查看 object 的指针。 Since this is not changed (only "prev" is edited, no new object with a new object address), it doesn't not rerender.由于这没有改变(只有“prev”被编辑,没有新的 object 地址的新 object),它不会重新渲染。 A solution would be to copy the object.一个解决方案是复制 object。

 let newUserInfo = Object.assign({}, prev); newUserInfo.works.map((p) => { if (p._id === work._id) { p.isEditing =.p;isEditing; } return p; }); return newUserInfo;

Disclaimer: maybe a deep copy is necessary...免责声明:也许需要深拷贝......

I just changed my code on workToggleHandler function and its working completely as i want.我刚刚更改了workToggleHandler function 上的代码,它完全按照我的意愿工作。 Below my code在我的代码下面

const [userInfo, setUserInfo] = useState(user);
const workToggleHandler = (work) => {
setUserInfo({
  ...userInfo,
  works: userInfo.works.map((p) => {
    if (p._id === work._id) {
      p.isEditing = !p.isEditing;
    }
    return p;
  }),
});
};

you can put into the useEffect when particular state is update then that effect will call您可以在特定 state 更新时放入 useEffect 然后该效果将调用

useEffect(()=>{ your code will go here }[userInfo]), useEffect(()=>{ 您的代码将在此处为 go }[userInfo]),

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

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