替换状态数组中的项目

时间:2018-03-15 21:45:15

标签: javascript reactjs

我已经研究过一段时间如果项目已经存在于状态数组中但是我找不到一个提议解决方案 https://codesandbox.io/s/4xl24j7r69

class RenameMerchantAsCustomer < ActiveRecord::Migration[5.1]
  def change
    rename_table :merchants, :customers

    rename_column :logs, :merchant_id, :customer_id
  end
end

我试图这样做,但它不起作用

import React from 'react';


class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [
        {
          "userId": 1,
          "id": 1,
          "title": "One",
          "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        },
        {
          "userId": 1,
          "id": 2,
          "title": "Two",
          "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
        },
      ]
    }
  }

  add = () => {
    this.setState(prevState => ({

      data: [...prevState.data,
      {
        "userId": 1,
        "id": 2,
        "title": "Two New",
        "body": "new data",
      }// this item already exist so I want to replace it to new data
      ]
    }))
  };
  render() {
    return (
      <div>
        {this.state.data.map((data) =>
          <ul key={data.id}>
            <li>{data.title}</li>
          </ul>
        )}
        <button onClick={this.add}>Replace</button>
      </div>
    );
  }
}
export default App;

如果项目已经存在,我该如何更新?

2 个答案:

答案 0 :(得分:4)

您可以找到该项目,只需使用object.assign

进行更新
let newUser1 = {
        "userId": 1,
        "id": 2,
        "title": "Two New",
        "body": "new data"
      }

this.setState(prevState => {
    let newData = prevState.data;
    let user = newData.find(d => d.id === newUser1.id);
    Object.assign(user, newUser1);
    return {data: newData};
})

答案 1 :(得分:1)

您必须递归创建深层副本,然后更新状态。

注意:
String nome; int i = 0; while(i<10 && !(nome = keyboard.next()).equalsIgnoreCase("fim")) { i++; // Either handle nome here directly, or add it to a list for later handling. } 函数不会创建深层副本,因此您必须创建一个新对象。 (我使用扩展运算符,还有另一种选择,例如slice)。

根据您的问题测试代码:

&#13;
&#13;
Object.assign()
&#13;
&#13;
&#13;

codesandbox link