반응의 상태 배열에서 항목 삭제


130

이야기는 밥, 샐리, 잭을 상자에 넣을 수 있어야한다는 것입니다. 상자에서 둘 중 하나를 제거 할 수도 있습니다. 제거하면 슬롯이 남지 않습니다.

people = ["Bob", "Sally", "Jack"]

이제 "밥"이라고 말하고 제거해야합니다. 새 배열은 다음과 같습니다.

["Sally", "Jack"]

내 반응 구성 요소는 다음과 같습니다.

...

getInitialState: function() {
  return{
    people: [],
  }
},

selectPeople(e){
  this.setState({people: this.state.people.concat([e.target.value])})
},

removePeople(e){
  var array = this.state.people;
  var index = array.indexOf(e.target.value); // Let's say it's Bob.
  delete array[index];
},

...

여기에 더 많은 것 (onClick 등)이 있으므로 최소한의 코드를 보여줍니다. 핵심 부분은 어레이에서 "Bob"을 삭제, 제거, 파괴하는 것이지만 removePeople()호출시 작동하지 않습니다. 어떤 아이디어? 나는 이것을보고 있었지만 React를 사용하고 있기 때문에 뭔가 잘못되었을 수 있습니다.

답변:


169

배열에서 요소를 제거하려면 다음을 수행하십시오.

array.splice(index, 1);

귀하의 경우 :

removePeople(e) {
  var array = [...this.state.people]; // make a separate copy of the array
  var index = array.indexOf(e.target.value)
  if (index !== -1) {
    array.splice(index, 1);
    this.setState({people: array});
  }
},

2
내 경우에는 그것이 있었다 : array.splice(array, 1);감사합니다
— 사일러

array.splice(array, 1);? 난 당신이 it..You이 ... 다른 변수를 사용한다 편집해야 할 것 같아요
— 레이온

61
React를 사용할 때 일반적으로 상태를 직접 변경하지 않아야합니다. 새 배열을 만들고 setState().
— iaretiga

2
이 경우 스프레드 연산자 대신 Array.from (this.state.items)을 사용하는 것이 좋습니다. 이는 Array.from이 특별히이 용도로 사용되기 때문입니다.
— Francisco Hodge

2
작은 제안으로, 원하지 않는 제거를 방지하기 위해 어레이를 연결하기 전에 "index! == -1"에 대한 확인을 추가하십시오.
— RoboBear

203

React를 사용할 때 상태를 직접 변경해서는 안됩니다. 객체 (또는 Array객체 인)가 변경된 경우 새 복사본을 만들어야합니다.

다른 사람들은 사용을 제안 Array.prototype.splice()했지만 그 방법은 Array를 변경하므로 splice()React와 함께 사용하지 않는 것이 좋습니다 .

Array.prototype.filter()새 어레이를 만드는 데 가장 사용 하기 쉬움 :

removePeople(e) {
    this.setState({people: this.state.people.filter(function(person) { 
        return person !== e.target.value 
    })});
}

42
예, 이것은 선언적 방법입니다. prevState 사용하는 다른 방법과 기능을 화살표 :this.setState(prevState => ({ people: prevState.people.filter(person => person !== e.target.value) }));
— 조쉬 모렐

9
이것은 결코 상태를 변경하지 않는 React 관용구에 따라 받아 들여지는 대답이어야합니다.
— lux

9
또는 색인 사용 :this.state.people.filter((_, i) => i !== index)
— mb21

2
가변 그 imutable 및 스플 라이스입니다 조각이
— Cassian

이 대답의 문제는 같은 이름을 가진 여러 사람이있는 경우 모두 제거한다는 것입니다. 인덱스를 사용하면 속는이있을 수 있습니다 경우에 안전
— klugjo

40

다음은 ES6를 사용한 Aleksandr Petrov의 반응에 대한 사소한 변형입니다.

removePeople(e) {
    let filteredArray = this.state.people.filter(item => item !== e.target.value)
    this.setState({people: filteredArray});
}

17

.splice배열에서 항목을 제거하는 데 사용 합니다. 를 사용 delete하면 배열의 인덱스는 변경되지 않지만 특정 인덱스의 값은undefined

접합부 () 메소드는 기존의 요소를 제거 및 / 또는 새로운 구성 요소를 추가하여 배열의 내용을 변경한다.

통사론: array.splice(start, deleteCount[, item1[, item2[, ...]]])

var people = ["Bob", "Sally", "Jack"]
var toRemove = 'Bob';
var index = people.indexOf(toRemove);
if (index > -1) { //Make sure item is present in the array, without if condition, -n indexes will be considered from the end of the array.
  people.splice(index, 1);
}
console.log(people);

편집하다:

justin-grant 에서 지적했듯이 경험상 직접 돌연변이를 사용 하지 마십시오. 나중에 this.state호출 setState()하면 사용자가 만든 돌연변이를 대체 할 수 있습니다. this.state불변 인 것처럼 취급하십시오 .

대안은에서 개체의 복사본을 만들고 복사본을 this.state조작하여를 사용하여 다시 할당하는 것 setState()입니다. Array#map, Array#filter등이 사용될 수있다.

this.setState({people: this.state.people.filter(item => item !== e.target.value);});

3
스플 라이스 또는 상태 변수를 직접 변경하는 방법을 사용하지 마십시오. 대신 배열의 복사본을 만들고 복사본에서 항목을 제거한 다음 복사본을 setState. 다른 답변에는이를 수행하는 방법에 대한 세부 정보가 있습니다.
— 저스틴 그랜트

12

반응에서 상태 배열에서 항목을 삭제하는 쉬운 방법 :

데이터가 데이터베이스에서 삭제되고 API를 호출하지 않고 목록을 업데이트하면 삭제 된 ID를이 함수에 전달하고이 함수는 목록에서 삭제 된 recored를 제거합니다.

export default class PostList extends Component {
  this.state = {
      postList: [
        {
          id: 1,
          name: 'All Items',
        }, {
          id: 2,
          name: 'In Stock Items',
        }
      ],
    }


    remove_post_on_list = (deletePostId) => {
        this.setState({
          postList: this.state.postList.filter(item => item.post_id != deletePostId)
        })
      }
  
}


1
이 3 년 된 질문에 대한 다른 8 개의 답변과 어떻게 다른지 설명해 주시겠습니까? 리뷰에서
— Wai Ha Lee

위의 코드에서 데이터의 새 배열을 다시 생성하지만 "deletePostId"를 건너 뜁니다.이 ID
— ANKIT-DETROJA

사용item.post_id !== deletePostId
— Nimish goel


3

값을 정의하는 것은 매우 간단합니다.

state = {
  checked_Array: []
}

지금,

fun(index) {
  var checked = this.state.checked_Array;
  var values = checked.indexOf(index)
  checked.splice(values, 1);
  this.setState({checked_Array: checked});
  console.log(this.state.checked_Array)
}

1

사용하는 것을 잊었습니다 setState. 예:

removePeople(e){
  var array = this.state.people;
  var index = array.indexOf(e.target.value); // Let's say it's Bob.
  delete array[index];
  this.setState({
    people: array
  })
},

그러나 filter배열을 변경하지 않기 때문에 사용하는 것이 좋습니다 . 예:

removePeople(e){
  var array = this.state.people.filter(function(item) {
    return item !== e.target.value
  });
  this.setState({
    people: array
  })
},

1
removePeople(e){
    var array = this.state.people;
    var index = array.indexOf(e.target.value); // Let's say it's Bob.
    array.splice(index,1);
}

자세한 정보는 Redfer 문서

당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.