programing

ReactJS에서 어레이 내의 개체를 업데이트하는 가장 좋은 방법은 무엇입니까?

codeshow 2023. 4. 2. 11:43
반응형

ReactJS에서 어레이 내의 개체를 업데이트하는 가장 좋은 방법은 무엇입니까?

어레이가 상태의 일부이고 해당 어레이에 개체가 포함되어 있는 경우 이러한 개체 중 하나를 변경하여 상태를 쉽게 업데이트하는 방법은 무엇입니까?

반응 관련 자습서에서 수정한 예:

var CommentBox = React.createClass({
  getInitialState: function() {
    return {data: [
      { id: 1, author: "john", text: "foo" },
      { id: 2, author: "bob", text: "bar" }
    ]};
  },
  handleCommentEdit: function(id, text) {
    var existingComment = this.state.data.filter({ function(c) { c.id == id; }).first();
    var updatedComments = ??; // not sure how to do this  

    this.setState({data: updatedComments});
  }
}

불변 도우미보다 Object.assign을 사용하여 이 작업을 수행하는 것이 좋습니다.

handleCommentEdit: function(id, text) {
    this.setState({
      data: this.state.data.map(el => (el.id === id ? Object.assign({}, el, { text }) : el))
    });
}

나는 이것이 스플라이스보다 훨씬 간결하고 인덱스를 알거나 발견되지 않은 사례를 명시적으로 처리할 필요가 없다고 생각한다.

모든 ES2018을 느끼고 계신다면 이 모든 것을 분산해서 할 수도 있습니다.Object.assign

this.setState({
  data: this.state.data.map(el => (el.id === id ? {...el, text} : el))
});

상태를 갱신할 때 중요한 것은 상태를 불변으로 취급하는 것입니다.당신이 보증할 수 있다면 어떤 해결책이라도 좋습니다.

불변성 헬퍼를 사용한 솔루션을 다음에 나타냅니다.

jsFiddle:

  var update = require('immutability-helper');

  handleCommentEdit: function(id, text) {
    var data = this.state.data;
    var commentIndex = data.findIndex(function(c) { 
        return c.id == id; 
    });

    var updatedComment = update(data[commentIndex], {text: {$set: text}}); 
    
    var newData = update(data, {
        $splice: [[commentIndex, 1, updatedComment]]
    });
    this.setState({data: newData});
  },

스테이트 어레이에 관한 다음의 질문도 도움이 됩니다.

난 이걸 어떻게 하는지 그리고 무슨 일이 일어나고 있는지 더 잘 설명하려고 노력 중이야.

  • 먼저 상태 배열에서 교체할 요소의 인덱스를 찾습니다.
  • 둘째,update그 지표의 요소
  • 셋째, 전화setState새로운 컬렉션과 함께
import update from 'immutability-helper';

// this.state = { employees: [{id: 1, name: 'Obama'}, {id: 2, name: 'Trump'}] } 

updateEmployee(employee) {
    const index = this.state.employees.findIndex((emp) => emp.id === employee.id);
    const updatedEmployees = update(this.state.employees, {$splice: [[index, 1, employee]]});  // array.splice(start, deleteCount, item1)
    this.setState({employees: updatedEmployees});
}

편집: 서드파티 라이브러리를 사용하지 않고 이 작업을 수행하는 훨씬 더 좋은 방법이 있습니다.

const index = this.state.employees.findIndex(emp => emp.id === employee.id);
employees = [...this.state.employees]; // important to create a copy, otherwise you'll modify state outside of setState call
employees[index] = employee;
this.setState({employees});

여러 가지 방법으로 할 수 있는데, 제가 주로 썼던 걸 보여드릴게요.react에서 어레이를 사용하는 경우 일반적으로 현재 인덱스 값을 가진 커스텀 속성을 전달합니다.다음 예에서는 data-index 속성 data-는 html 5 규약입니다.

예:

//handleChange method.
handleChange(e){
  const {name, value} = e,
        index = e.target.getAttribute('data-index'), //custom attribute value
        updatedObj = Object.assign({}, this.state.arr[i],{[name]: value});
      
  //update state value.
  this.setState({
    arr: [
      ...this.state.arr.slice(0, index),
      updatedObj,
      ...this.state.arr.slice(index + 1)
    ]
  })
  }

언급URL : https://stackoverflow.com/questions/28121272/whats-the-best-way-to-update-an-object-in-an-array-in-reactjs

반응형