簡體   English   中英

ReactJs-如何更新數組中的狀態?

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

我正在用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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM