2017-10-10 57 views
1

我想渲染一個ItemList,但不知道爲什麼反應不喜歡我的代碼。它說:渲染ItemList時無法編譯

enter image description here

這是我的列表組件代碼:

class RecipeList extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     recipes: [{ 
      url: 'http://via.placeholder.com/300x300', 
      title: '1st Title', 
      description: 'some decription 1' 
     },{ 
      url: 'http://via.placeholder.com/300x300', 
      title: '2nd Title', 
      description: 'some decription 2' 
     },{ 
      url: 'http://via.placeholder.com/300x300', 
      title: '3rd Title', 
      description: 'some decription 3' 
     }] 
    } 
    } 

    const Items = recipes.map((recipe, index) => { 
    return <RecipeListItem 
      key={index} 
      recipe={recipe} 
      /> 
    }); 
    return (
     <div> 
     <div> 
      {Items} 
     </div> 
     </div> 
    ) 
} 

export default RecipeList; 

我創建一些示例數據,然後通過分配結果爲const項目迭代。

+0

是的,看看Austin說了些什麼,但最重要的是,你不應該把索引作爲列表中的關鍵字。你最好使用'recipe.title'之類的東西。這有助於React瞭解發生更改時的更新內容。否則,它需要重新渲染一切。 – baron816

回答

1

看起來你缺少你render功能:

class RecipeList extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     recipes: [{ 
      url: 'http://via.placeholder.com/300x300', 
      title: '1st Title', 
      description: 'some decription 1' 
     },{ 
      url: 'http://via.placeholder.com/300x300', 
      title: '2nd Title', 
      description: 'some decription 2' 
     },{ 
      url: 'http://via.placeholder.com/300x300', 
      title: '3rd Title', 
      description: 'some decription 3' 
     }] 
    } 
    } 

    render() { 
    const Items = this.state.recipes.map((recipe, index) => { 
     return (
     <RecipeListItem 
      key={index} 
      recipe={recipe} 
     /> 
    ); 
    }); 

    return (
     <div> 
     <div> 
      {Items} 
     </div> 
     </div> 
    ); 
    } 
} 

export default RecipeList; 

也是你的地圖應該循環通過this.state.recipes,而不是僅僅recipes

+0

這就是最完美的答案! – karolis2017