简体   繁体   English

如何有选择地为具有两个对象数组的对象设置状态?

[英]How to selectively setState for an object with two array of objects?

How would I add new objects to the data: [] using setState() for the following code or replace data entirely??我将如何向数据中添加新对象:[] 使用 setState() 为以下代码或完全替换数据?

    const [tableState, setTableState] = useState<TableState>({
    columns: [
      { title: "First Name", field: "firstName" },
      { title: "Last Name", field: "lastName" },
    ],
    data: [
      {
        firstName: "John",
        lastName: "Doe",
      },
      {
        firstName: "Jane",
        lastName: "Doe",
      },
    ],
  });

setState(prevState => ({...prevState.tableState, ???}))

You are mixing between hooks and conventional setState .你在hooks和传统的setState之间混合。

From the above code, you should be updating your state using setTableState function instead.从上面的代码中,您应该使用setTableState函数来更新您的状态。

setTableState(prevState => ({
  ...prevState,
  data: [
    ...prevState.data,
    {
      firstName: 'New FirstName',
      lastName: 'New Last Name'
    }
  ]
}))

Say you have a new user, Joe Bloggs.假设您有一个新用户 Joe Bloggs。 It would look like this (note that the setter is setTableState — the setter you got from useState — not setState ):它看起来像这样(请注意,setter 是setTableState — 您从useState获得的 setter — 而不是setState ):

setTableState(prevState => ({
    ...prevState, 
    data: [
        ...prevState.data, {
            firstName: "Joe",
            lastName: "Bloggs"
        }
    ]
}));

What that does:有什么作用:

  1. Creates a new object which is a shallow copy of prevState , but创建一个新对象,它是prevState的浅拷贝,但是

  2. With a new data property, that有了新的data属性,

  3. Has the original data, plus the new object有原始数据,加上新对象


But stepping back a bit: That state item is probably too complicated.但是退一步说:那个状态项可能太复杂了。 With hooks and useState , you usually want to keep your state really finely-grained.使用 hooks 和useState ,您通常希望保持状态非常细粒度。 In this case, I think there are at least two separate state items:在这种情况下,我认为至少有两个单独的状态项:

const [columns, setColumns] = useState<ColumnType[]>([
    { title: "First Name", field: "firstName" },
    { title: "Last Name", field: "lastName" },
]);
const [data, setData] = useState<DataType[]>([
    {
        firstName: "John",
        lastName: "Doe",
    },
    {
        firstName: "Jane",
        lastName: "Doe",
    },
]);

And you'd set new data state like this:你会像这样设置新的data状态:

setData(data => [
    ...data,
    {
        firstName: "Joe",
        lastName: "Bloggs"
    }
]);

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

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