방법

2017-12-20 24 views
0
내가 현재의 배열을 확인 CONSOLE.LOG을 사용하여 항목을 제거하기 위해 X 버튼을 클릭하면 내 응용 프로그램에서는, 할 목록 응용 프로그램을 만드는 반응 사용하고

반응하여 일 목록에서 항목을 제거하기 위해, 나는 볼 수 있습니다 배열은 내가 배열의 목록에서 제거 제거 할 항목 제대로 업데이트되지만 돔 단지 내가 대신 전체 배열방법

import React from 'react'; 
import ReactDom from 'react-dom'; 

class TodoList extends React.Component{ 
    constructor(props){ 
     super(props); 
     this.state={ 
      todoList:[], 
      todo:'' 
     } 
    }; 

    onValueChange=(e)=>{ 
     const todo=e.target.value; 
     this.setState({todo}) 
    }; 

    removeItem=(props)=>{ 
     this.setState({todoList:this.state.todoList.splice(props,1)}) 
     console.log(this.state.todoList) 
    }; 

    onSubmit=(e)=>{ 
     e.preventDefault(); 
     const {todoList,todo}=this.state 
     this.setState({todoList:[...todoList,todo]}) 
     this.setState({todo:''}) 
     console.log(this.state.todoList) 
    }; 

    render(){ 
     const myList=this.state.todoList.map((todo,index)=>(
      <li key={index}> 
       {todo} 
       <button onClick={()=>this.removeItem(index)}>x</button> 
      </li> 
     )) 
     return (
      <div> 
       <form onSubmit={this.onSubmit}> 
        <input 
         type="text" 
         value={this.state.todo} 
         onChange={this.onValueChange} 
         autoFocus 
         placeholder='todo' 
        /> 
       </form> 
       <ol> 
        {myList} 
       </ol> 
      </div> 
     ) 
    }; 
}; 

ReactDom.render(<TodoList/>,document.getElementById('app')); 

이의 제거 할 항목을 렌더링 사진

enter image description here입니다

그림에서 당신은 C 것을 알 수 있습니다 onsole 제거 '5'항목을 가지고있는 배열을 보여 주지만, 화면 만 항목을 보여 '5'대신 항목 (1)의 4

+0

확인이 https://stackoverflow.com/questions/43893508/remove-items-form-the-list-in-react-js/43893804#43893804 –

+1

스플 라이스는 제거 된 항목을 반환합니다. splice를 먼저 실행 한 다음 – cdoshi

+0

배열을 console.log로 지정하지 마십시오! setState는 비동기 메서드이며 setState 바로 다음에 상태 변경을 볼 수 없습니다. componentDidUpdate 기능에 당신의 setTimeout과 같은 방법을 사용할 수 있습니다 (() => CONSOLE.LOG (this.state)) 또는 인쇄 상태입니다. –

답변

3

removeItem

removeItem = (props)=> { 
    this.state.todoList.splice(props, 1) 
    this.setState({todoList: this.state.todoList}) 
    console.log(this.state.todoList) 
}; 

Array.prototype.splice() 방법은 장소에 배열을 수정 수정.

반환 값

삭제 요소들을 포함하는 배열. 하나의 요소가 가 제거되면, 하나 개의 원소의 배열을 반환한다. 어떤 요소가 가 제거되지 않은 경우는 하늘의 배열이 반환됩니다.

+0

고맙습니다. – Nhat

1

스플 라이스 기능은 최종 배열을 반환하지 않고 대신 조작이 수행되는 배열을 변경합니다.

당신이 this.state 중 todoList를 추출하고 스플 라이스 작업을 수행하는 경우가 좋다.

removeItem=(props)=>{ 
    const { todoList } = this.state; 
    todoList.splice(props, 1); 
    this.setState({ 
     todoList, 
    }); 
    console.log(this.state.todoList) 
}; 

위의 대답은 정상적으로 작동합니다. 그러나 이것은 동일한 것을보다 단순하게 구현 한 것입니다.