如何迭代密钥对集合?

时间:2017-10-11 02:23:05

标签: reactjs

我已经定义了一些示例数据(集合)并尝试迭代,但得到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>

    );
  }
}

1 个答案:

答案 0 :(得分:1)

您的食谱需要独特的钥匙。请尝试以下

    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>

      );
    }
  }

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