简体   繁体   English

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

[英]ReactJs - How to update state in array?

I'm creating a Page Builder with React. 我正在用React创建一个页面构建器。

I have a component which contains the structure of the page. 我有一个包含页面结构的组件。

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'
                           }
                      }
                   }
               }
           }
        }
    };
},
.....
});

I have a system with drag'n drop to put a new element on the page and it works. 我有一个具有拖放功能的系统,可以在页面上放置一个新元素,并且可以正常工作。 But when the new element is dropped I want to update the state to add a new item in the array. 但是当删除新元素时,我想更新状态以在数组中添加新项。

So how can I push a new item ? 那么我该如何推新项目呢? I did a test with that : 我做了一个测试:

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

But I have an error : 但是我有一个错误:

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

Can you help me ? 你能帮助我吗 ?

Thank you. 谢谢。

Instead of using an object in your state you should change it to the array like below : 与其在您的状态下使用对象,不如将其更改为如下所示的数组:

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

Where the items it's an array of objects. 其中的项目是一个对象数组。 And then you will be able to add new items to an array. 然后,您将能够向阵列添加新项目。

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
})

The whole example is here . 整个例子在这里

I hope it will help you! 希望对您有帮助!

Thanks 谢谢

You'll start to get headaches if you directly mutate the state of your application. 如果直接更改应用程序的状态,就会开始感到头痛。 If you forget to call this.setState then it won't re-render! 如果您忘记调用this.setState ,它将不会重新渲染!

Assuming you can't use an array (which would be easier), then you'll have to generate a unique key if you want to add another item to the object. 假设您不能使用数组(这会更容易),那么如果您想向对象添加另一个项目,则必须生成一个唯一键。

// 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 });

This is even easier with ES7/Babel . 使用ES7 / Babel甚至更容易。

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

this.setState({ items });

You can generate a similar unique ID to the one you have there using Math.random . 您可以使用Math.random生成与您拥有的唯一ID相似的唯一ID。

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

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

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