如何迭代密钥对集合?

问题描述:

我已经定义了一些样本数据(集合),并试图通过迭代,但得到Failed to Compile,它的指向render() {在这个组件:如何迭代密钥对集合?

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

    render() { 
    const recipeIds = Object.keys(this.state.recipes); 

    const Items = recipeIds.map((recipe) => { 
     return (
     <RecipeListItem 
      key={recipe} 
      recipe={recipe} 
     /> 
    ); 
    }); 

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

    ); 
    } 
} 

你需要为你的食谱唯一键。请尝试以下操作

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

    render() { 
     const recipeIds = Object.keys(this.state.recipes); 

     const Items = recipeIds.map((key) => { 
     return (
      <div 
      key={key}> 
      {this.state.recipes[key].id} 
      </div> 
     ); 
     }); 

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

    ); 
    } 
    } 

编辑:更新了代码以提供整个班级。