2017-04-19 2 views
0

CODE :잘못된 색인이 지정된 이유는 무엇입니까?

handleDeleteClick: function(index) { 
     var newRecipesArray = this.state.recipesArray; 
     newRecipesArray.splice(index-1,1); 
     this.setState({ 
      recipesArray: newRecipesArray 
     }); 
    }, 
    render: function() { 
     var i = 0; 
     var that = this; 

     var recipes = this.state.recipesArray.map(function(item) { 
      i++ 
      return (
       <div key={"div"+i} className="table"> 
        <Recipe key={i} name={item.name} ingredients={item.ingredients} /> 
        <button key ={"edit"+i} onClick={() => { that.handleEditClick(i)}} className="btn edit btn-primary">Edit</button> 
        <button key ={"delete"+i} onClick={() => { that.handleDeleteClick(i)}} className="btn delete btn-danger">Delete</button> 
       </div> 
      ); 
     }); 

     return (
      <div> 
       <h1>React.js Recipe Box</h1> 
       <button className="btn btn-primary" onClick={this.handleClick}>Add Recipe</button> 
       <table> 
        <tbody> 
         <tr> 
          <th>RECIPES</th> 
         </tr> 
        </tbody> 
       </table> 
       {recipes} 
       { this.state.adding ? <AddRecipe handleClose={this.handleClose} handleAdd={this.handleAdd} /> : null } 
       { this.state.editing ? <EditRecipe currentIndex = {this.state.currentIndex} handleClose={this.handleClose} handleEdit={this.handleEdit}/> : null } 
      </div> 
     ); 
    }, 
}); 

상황 :

내가 삭제를 클릭, 그것은 삭제 특정에 연결해야 하나 대신 삭제 마지막 요소는 항상 단추.

어디에서 실수가 있었으며 어떻게 수정합니까?

+0

레시피에 고유 한 ID가 있습니까? 색인에 대한 색인은 잘못된 선택입니다 – Thomas

답변

1

Map은 두 번째 매개 변수로 인덱스를 제공하므로 별도의 인덱스 변수가 필요하지 않습니다. 또한 모든 요소에 대해 키가 필요하지 않고 부모 요소 만 필요합니다.

handleDeleteClick: function(index) { 
     var newRecipesArray = this.state.recipesArray; 
     newRecipesArray.splice(index,1); 
     this.setState({ 
      recipesArray: newRecipesArray 
     }); 
    }, 
    render: function() { 

     var that = this; 

     var recipes = this.state.recipesArray.map(function(item, i) { 

      return (
       <div key={"div"+i} className="table"> 
        <Recipe name={item.name} ingredients={item.ingredients} /> 
        <button onClick={() => { that.handleEditClick(i)}} className="btn edit btn-primary">Edit</button> 
        <button onClick={() => { that.handleDeleteClick(i)}} className="btn delete btn-danger">Delete</button> 
       </div> 
      ); 
     }); 
+0

당신은 틀린 것입니다. 슬프게도, 이것은 구성 요소의 동작에 아무런 변화가 없습니다. 마지막 요소는 여전히 첫 번째 삭제 버튼을 클릭해도 삭제되는 요소입니다./원인은 무엇입니까? – Coder1000

+0

함수에서 인덱스를보고 로그 할 수 있습니까? –

+0

고정! 완벽 : D – Coder1000

관련 문제