ReactJs-如何更新数组中的状态

ReactJs - How to update state in array?

本文关键字:数组 状态 更新 何更新 ReactJs-      更新时间:2023-09-26

我正在用React创建一个页面生成器。

我有一个包含页面结构的组件。

var LayoutPage = React.createClass({
getInitialState: function getInitialState() {
    return {
      items: {
          '78919613':{
              id: '78919613',
              component : 'OneColumn',
              cols:{
                  '565920458':{
                      id: '565920458',
                      content:{
                          '788062489':{
                              id: '788062489',
                              component : 'Text',
                              params: 'Lorem ipsum'
                           },
                           '640002213':{
                              id: '640002213',
                              component : 'Text',
                              params: 'Lorem ipsum'
                           }
                      }
                   }
               }
           }
        }
    };
},
.....
});

我有一个拖放系统,可以在页面上添加一个新元素,它很有效。但是当新元素被删除时,我想更新状态以在数组中添加一个新项。

那么我该如何推送一个新项目呢?我用它做了一个测试:

this.state.items.push({.....});

但我有一个错误:

TypeError: this.state.items.push is not a function

你能帮我吗?

谢谢。

与其在您的状态中使用对象,不如将其更改为如下所示的数组:

    this.state = {
        items: [ // items array
        {
          id: 1,
          name: "Stack"
        },
        {
          id: 2,
          name: "Overflow"
        }],
        count: 3,  // another state
        textValue : ''  // and this is state too
    }

在项目所在的位置,它是一个对象数组。然后,您将能够向数组中添加新项目。

const newItem = {
    id : this.state.count,
  name: this.state.textValue
};
const newArr = this.state.items.concat(newItem);
this.setState({
    items: newArr,
    textValue: '',
    count: this.state.count + 1
})

整个示例是此处

我希望它能帮助你!

感谢

如果直接更改应用程序的状态,您将开始感到头疼。如果忘记调用this.setState,则它不会重新渲染!

假设你不能使用数组(这会更容易),那么如果你想向对象添加另一个项,你就必须生成一个唯一的键。

// create a new copy of items based on the current state
var newItems = Object.assign({}, this.state.items),
    newItem = { id: '', component: '', cols: {} },
    uniqueId = generateUniqueId();
// safely mutate the copy
newItems[uniqueId] = newItem;
// update the items property in state
this.setState({ items: newItems });

有了ES7/Babel,这就更容易了。

const newItem = { id: '', component: '', cols: {} },
      uniqueId = generateUniqueId(),
      items = { [uniqueId]: newItem, ...this.state.items };
this.setState({ items });

您可以使用Math.random生成与现有ID类似的唯一ID。

function generateUniqueId() {
  // removing leading '0.' from number
  return Math.random()
    .toString()
    .slice(3);
}