2017-10-10 11 views
1

アイテムをリストに追加できましたが、それをレンダリングできませんでした。 マイApp.js:はアイテムを状態に追加しましたがレンダリングできません

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     recipes: [{ 
     ...sample data... 
     }] 
    } 
    } 

    createRecipe(recipe) { 
     this.state.recipes.push({ 
     recipe 
     }); 
     this.setState({ recipes: this.state.recipes }); 
    } 

    render() { 
    ... 

export default App; 

と私のRecipeAdd:

onSubmit = (e) => { 
    e.preventDefault(); 
    if (!this.state.url || !this.state.title || !this.state.description) { 
     this.setState(() => ({ error: 'Please provide url, title and description.'})); 
    } else { 
     this.setState(() => ({ error: ''})); 
     this.props.createRecipe({ 
     url: this.state.url, 
     title: this.state.title, 
     description: this.state.description 
     }); 
    } 
    } 
    render() { 
     return (
     <div> 
      ...form... 
     </div> 
    ) 
    } 
} 

で反応のdevのツール

export default class RecipeAdd extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     url: '', 
     title: '', 
     description: '', 
     error: '' 
    }; 
    } 

...イベントハンドラは...私はレシピが追加されると見ます'レシピ'。新しいレシピを正しく追加するためにcreateRecipeアクションをどのように変更する必要がありますか? :あなたは、余分なオブジェクト内のレシピをラップしているよう

enter image description here

答えて

3

に見えます。スクリーンショットでは、インデックス3に余分なrecipeプロパティがあることがわかります。

それはもっとこのようにする必要があります - ちょうど.pushレシピオブジェクトに直接:

createRecipe(recipe) { 
    this.state.recipes.push(recipe); 
    this.setState({ recipes: this.state.recipes }); 
} 

さらに良いことには代わりにconcatを使用することにより、直接、状態オブジェクトを変異しないように次のようになります。

createRecipe(recipe) { 
    this.setState({ 
    recipes: this.state.recipes.concat([recipe]) 
    }); 
} 
+0

' .concat'は新しい配列を返しますので、これを避けるのは良いことです。基本的には、配列のコピーを作成してそれを続けることと同じです。上記のコードはうまくいくはずです。パラメータは配列である必要があることを覚えておく必要があります。そのため、配列を使用するために配列にラップする必要があります。 –

+0

パーフェクト。ありがとう! – karolis2017

関連する問題