2016-08-16 2 views
0

나는 꽤 이상한 경우를 만나고 그것을 일으킬 수있는 것을보고 싶어합니다. ReactJS에서 조리법을 포함 할 수있는 조리법 상자를 만들고 있습니다. 다음과 같은 초기 레시피로 시작합니다 :Reactjs는 이전에 삽입 된 객체에 삽입 된 객체를 복제합니다.

다음으로 이름과 재료가 포함 된 레서피를 추가 할 수 있습니다. 양식. AddRecipe 구성 요소에서 : 성분은 쉼표의로 구분 형태로 입력 할 수 있습니다

<Form > 
    <ControlLabel>Recipe Name</ControlLabel> 
      <FormControl 
     type="text" 
     value={this.state.value} 
     placeholder="Beef Cheese" 
     onChange={this.handleRecipeNameChange} 
     /> 
    <hr/> 
    <FormGroup controlId="formControlsTextarea"> 
    <ControlLabel>Ingredients</ControlLabel> 
    <FormControl onChange={this.handleIngredientsChange} 
componentClass="textarea" placeholder="salt,pepper,cheese,beef" /> 
</FormGroup> 
    <ButtonToolbar> 
<Button onClick={this.handleAddRecipe} bsStyle="primary">Add Recipe</Button> 
    <Button onClick={this.closeModal}>Cancel</Button> 

.

AddRecipe 성분에서 : 여기 폼 핸들 방법이다

handleAddRecipe: function() { 
    this.closeModal(); 
    this.props.addRecipe(this.state.recipe); 
    }, 

    handleRecipeNameChange: function(e) { 
    var recipe = this.state.recipe; 
    recipe.name = e.target.value; 
    this.setState({recipe: recipe}); 
    }, 

    handleIngredientsChange: function(e) { 
    var recipe = this.state.recipe; 
    recipe.ingredients = e.target.value.split(","); 
    this.setState({recipe: recipe}); 
    } 

마지막 addRecipe AddRecipe 컴포넌트로부터 레시피를 수신하고, 레시피 객체의 레시피 어레이에 추가한다 (레시피)이있다. 조리법의 각 고유 ID가 있어야 : 나는 한 레시피를 추가하면 3의 고유 ID를 가져옵니다

addRecipe: function(recipe) { 
    var currentRecipes = this.state.recipes; 
    console.log("currentRecipes "); 
    console.log(currentRecipes); 
    recipe.id = currentRecipes.length; 
    currentRecipes.push(recipe); 
    console.log("recipe added: "); 
    console.log(recipe); 
    console.log(recipe.id + " last id!"); 
    this.setState({recipes: currentRecipes}); 
    } 

을이 출력은,이 괜찮 내가 예상대로 :

recipes: [{ 
     id: 0, 
     name: "Carbonana", 
     ingredients: ["Spaghetti", "Banana-sauce", "Bacon", "Cream", "Oregano"] 
     }, { 
     id: 1, 
     name: "Roasted duck with sweet potatoes", 
     ingredients: ["Duck", "Sweet chili sauce", "Small potatoes", "Sugar", "Butter"] 
     }, { 
     id: 2, 
     name: "Baked potatoes", 
     ingredients: ["Baking potatoes", "Bacon", "Creme Fraiche", "Garlic", "Onions"] 
     }, { 
     id: 3, 
     name: "Something new and exciting!", 
     ingredients: ["More beef", "Onions"] 
     }] 

이제 AddRecipe 구성 요소에서 양식을 다시 열고 새 레서피를 입력하십시오. 그러나 이번에는 단순히 동일한 객체를 다시 삽입합니다.

recipes: [{ 
      id: 0, 
      name: "Carbonana", 
      ingredients: ["Spaghetti", "Banana-sauce", "Bacon", "Cream", "Oregano"] 
      }, { 
      id: 1, 
      name: "Roasted duck with sweet potatoes", 
      ingredients: ["Duck", "Sweet chili sauce", "Small potatoes", "Sugar", "Butter"] 
      }, { 
      id: 2, 
      name: "Baked potatoes", 
      ingredients: ["Baking potatoes", "Bacon", "Creme Fraiche", "Garlic", "Onions"] 
      }, { 
      id: 4, 
      name: "Something even more new and improved!!", 
      ingredients: ["Day old potatoes", "salt"] 
      }, { 
      id: 4, 
      name: "Something even more new and improved!!", 
      ingredients: ["Day old potatoes", "salt"] 
      }] 

내가 알아챈 것은 이전에 입력 한 모든 객체에서 가장 최근에 입력 한 객체를 복제한다는 것입니다. 왜 이런거야? 당신은 http://codepen.io/Hylleh/pen/pbqNbO?editors=1010

+0

당신이 VAR currentRecipes = this.state.recipes'뭔가를 수행하여 상태 개체 자체를 변이 코드에서 몇 가지 포인트가 있습니다 그래서 같은 App.addRecipe 기능을 수정하는 것 . 그러한 모든 문장을'var currentRecipes = Object.assign ([], this.state.recipes);'로 변경 한 다음 다시 시도하십시오. –

답변

0

AddRecipe 구성 요소가 this.props.addRecipe를 사용하고 그 상태로 참조를 전달한다는 사실은 새로운 조리법을 추가 할 수없는 이유 문제를 작업에 페이지를 볼 수 있습니다.

귀하의 App 구성 요소는이 참조를 받아 계속 반복해서 배열에 추가합니다. 따라서이 배열의 인덱스 2 이전의 모든 항목은 항상 동일한 id, nameingredients 속성을 공유하므로 동일한 AddRecipe 상태와 완전히 동일한 참조가됩니다. 이 조리법 각각에 대해 id을 키로 사용하기 때문에 React는 추가하는 모든 조리법이 마지막 조리개와 동일한 키를 공유하기 때문에 추가 한 첫 번째 조리법 이후에 조리법을 렌더링하지 않습니다.

경고 : flattenChildren (...) : 해당 페이지에서 콘솔을 열면

, 당신은이 개 조리법을 추가하려고 후이 오류를 볼 수 있습니다 발생했습니다 두 아이를 같은 키, 4 . 하위 키는 고유해야합니다. 두 자녀가 키를 공유하면 첫 번째 자녀 만 사용됩니다.

이 문제의 해결책은 App 구성 요소의 상태에 AddRecipe 구성 요소의 상태에 대한 참조를 저장하지 않는 것입니다.`currentRecipes`을 수정 한 후 '와;

addRecipe(recipe) { 
    // Clone passed state reference and set id to the correct value 
    const newRecipe = Object.assign({}, recipe, { 
     id: this.state.recipes.length 
    }); 

    // Replace recipes with a new array that has newRecipe appended at the end 
    this.setState({ 
     recipes: [...this.state.recipes, newRecipe] 
    }); 
} 
+0

고마워 지금은 효과가있다. 나는 주변을 지나가고 있다는 것을 몰랐다. – Hylle

+0

도와 드리겠습니다 :) 문제가 해결되면 답변을 수락하십시오! –

관련 문제