이야기는 밥, 샐리, 잭을 상자에 넣을 수 있어야한다는 것입니다. 상자에서 둘 중 하나를 제거 할 수도 있습니다. 제거하면 슬롯이 남지 않습니다.
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를 사용하고 있기 때문에 뭔가 잘못되었을 수 있습니다.
답변
배열에서 요소를 제거하려면 다음을 수행하십시오.
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});
}
},
답변
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
})});
}
답변
다음은 ES6를 사용한 Aleksandr Petrov의 반응에 대한 사소한 변형입니다.
removePeople(e) {
let filteredArray = this.state.people.filter(item => item !== e.target.value)
this.setState({people: filteredArray});
}
답변
.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);});
답변
반응에서 상태 배열에서 항목을 삭제하는 쉬운 방법 :
데이터가 데이터베이스에서 삭제되고 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)
})
}
}
답변
Chance Smith가 말한 것처럼 ‘splice’를 사용하여 언급 한 일부 답변은 배열을 변경했습니다. 원본 배열의 복사본을 만드는 메서드 호출 ‘slice’ ( ‘slice’에 대한 문서는 여기에 있음) 를 사용하는 것이 좋습니다
.
답변
값을 정의하는 것은 매우 간단합니다.
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)
}
