React.js将新元素推送到嵌套状态

时间:2018-12-04 01:42:57

标签: javascript reactjs

我是JavaScript的新手,会做出反应,我尝试将新元素推入状态内的数组,但没有成功。

state = {
 columns: [
  {
   id: 122,
   items: [{text:'abc'},{text:'cde'}]
  },
  {
   id: 143,
   items: []
  }
 ]
 }

   addItem(columnId,text) {
     const newItem = {text: text}
   //this.setState(...)
   }

基本上,我有一个具有给定columnId和一些文本内容的addItem函数,我想将一个新项目推送到具有给定columnId的列内的项目数组中。

我听说在不可变帮助器的帮助下会容易得多,对吗?

4 个答案:

答案 0 :(得分:1)

您可以从状态中获取价值并推动其发展。

然后this.setState进行重新渲染。

addItem(columnId, text) {
    const newItem = {text};   
    let columns = this.state.columns;
    let findColumn = columns.find(({id})=>id === columnId);
    if( findColumn ) {
        findColumn.items.push( newItem );
    }
    else {
        columns.push({id:columnId, items:[newItem]});
    }
    this.setState({columns});
}

如果要收紧。我们可以使用解构。

addItem(columnId, text) {
    let {columns} = this.state;
    let findColumn = columns.find(({id})=>id === columnId);
    if( findColumn ) {
        findColumn.items.push( {text} );
    }
    else {
        columns.push({id:columnId, items:[{text}]});
    }
    this.setState({columns});
}

答案 1 :(得分:1)

如果您学习诸如mapfilterspread syntaxObject.assign之类的方法,则不需要任何不变性助手。使用其中一些(合适的),您可以做任何您想做的事情而不会改变状态。

const addItem = (columnId, text) => {
  // We are mapping the columns from the state.
  const newColumns = this.state.columns.map(column => {
    // If id does not match just return the column.
    if (column.id !== columnId) return column;
    // Else, return a new column object by using spread syntax.
    // We spread the column (preserve other properties, and create items again
    // using spread syntax. Spread the items, add the new text object.
    return { ...column, items: [...column.items, { text }] };
  });
  // Lastly, set the state with newColumns.
  this.setState({ columns: newColumns });
};

没有评论:

const addItem = (columnId, text) => {
  const newColumns = this.state.columns.map(column => {
    if (column.id !== columnId) return column;
    return { ...column, items: [...column.items, { text }] };
  });
  this.setState({ columns: newColumns });
};

答案 2 :(得分:0)

您可以创建状态的副本并进行修改:

addItem(columnId,text) {
   let newColums = [...this.state.columns]; // Create a copy of the state using spread operator
   newColumns[columnId].items.push({text: text}) // Add the new item
   this.setState({columns:newColumns}) // Set the state
}

答案 3 :(得分:0)

weights = []
length = len(layers_size)
#appreciate loop starting in 1 since you dont need 
#weights #in the entry layer

#runs layers_size times - 1
for i in range(1, length):
#Gives the amount of neurons for each layer
for j in range(0, layers_size[i]):
    #Get the amount of neurons from the previous layer to 
    # the actual neuron so it saves layers_size[i] - 1 
    # numWeights for the actual neuron...
    weights[i][j] = random...