質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

2回答

719閲覧

GatsbyJS(ReactJS)で重複している要素を除外して表示させたい。

1042limit

総合スコア29

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

0クリップ

投稿2019/01/10 07:47

お世話になります。
GatsbyJSでカテゴリー一覧を表示するコンポーネントを作成しています。
しかし、重複して表示されてしまい上手くいきません。
ご教授いただければ幸いです。

import React from "react"; import { Link } from "gatsby"; import "./Category.css"; class Category extends React.Component { getPostList() { let postList = []; this.props.postEdges.forEach(postEdge => { postList.push({ category: postEdge.node.frontmatter.category,     categoryslug: postEdge.node.frontmatter.categoryslug, }); }); return postList; } render() { const postList = this.getPostList().filter(function (category, index, self) { return self.indexOf(category) === index; }); return ( <div className="grid"> postList.map(post => ( <div className="item"> <p>{post.category}</p> </div> ))} </div> ); } } export default Category;

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jun68ykt

2019/01/10 12:46

こんにちは。 this.props.postEdges で渡されてくる配列の各要素がどのような構造になっているのかを知りたいので、postEdges のサンプルを質問に追記して頂ければと思います。
1042limit

2019/01/10 15:03

お世話になります。 GraphiQLのデータを提示させていただきます。 { "data": { "allMarkdownRemark": { "edges": [ { "node": { "fields": { "slug": "/the-butterfly-of-the-edge", "date": "2017-03-19T15:00:00.000Z" }, "excerpt": "Hanc indeploratum seram Amphitryoniadae tremulis pauperque manum Cognoscenti audeat ulterius sublimia terga potiorque saxo あいうえお\nLorem…", "timeToRead": 1, "frontmatter": { "title": "The Butterfly of the Edge", "tags": [ "programming", "more tags", "testing", "another one", "stuff", "other" ], "cover": "https://unsplash.it/1152/300/?random?TheButterflyoftheEdge", "date": "17/03/2017", "category": "tech", "categoryslug": "tech" } } }, { "node": { "fields": { "slug": "/the-fairys-witches", "date": "2002-04-19T15:00:00.000Z" }, "excerpt": "Eram mora tuas in inter ferens caterva Ait oculos Lorem markdownum. Dedit caput, saxa lenis adhibere negarunt substiterat et ab\ntestes…", "timeToRead": 1, "frontmatter": { "title": "The Fairy's Witches", "tags": null, "cover": "https://unsplash.it/1152/300/?random?FaityWitch", "date": "02/04/2017", "category": "something", "categoryslug": "something" } } }, { "node": { "fields": { "slug": "/random-project-4-with-super-long-title-phase-one", "date": "2002-03-19T15:00:00.000Z" }, "excerpt": "Artificem honorati ore temperat Lycus quam antiquum Mendaci pinu ipsi nunc Lorem markdownum supplex. Care ferre nos praemia detestatur…", "timeToRead": 2, "frontmatter": { "title": "Random project 4 With Super Long Title Phase One", "tags": [ "say hi" ], "cover": "https://unsplash.it/1152/300/?random?SuperLong", "date": "02/03/2017", "category": "random", "categoryslug": "random" } } }, { "node": { "fields": { "slug": "/angels-of-mist", "date": "2001-03-19T15:00:00.000Z" }, "excerpt": "Ab dicemur cura Mane oscula anxia Lorem markdownum alius, non voluntas supremaque : canes ager cingere quis;\nrerum? Nunc nec ferunt verbis…", "timeToRead": 2, "frontmatter": { "title": "Angels of Mist", "tags": [ "cheese", "other" ], "cover": "https://unsplash.it/400/300/?random?AngelsofMist", "date": "01/03/2017", "category": "test3", "categoryslug": "test3" } } }, { "node": { "fields": { "slug": "/big-sample-test", "date": "2001-03-19T15:00:00.000Z" }, "excerpt": "NOTE: This \"post\" is based on Markdown Cheatsheet and is meant to test styling of Markdown generated documents. This is intended as a…", "timeToRead": 8, "frontmatter": { "title": "Big Test", "tags": [ "test", "huge" ], "cover": "https://unsplash.it/400/300/?random?BigTest", "date": "01/03/2018", "category": "moar", "categoryslug": "moar" } } }, { "node": { "fields": { "slug": "/birch-in-the-roses", "date": "2001-03-19T15:00:00.000Z" }, "excerpt": "Domos primus caelum taedia Accipit alto fecerat mutato centauri haerent dominoque Sicyonius color Publica animalia suoque sub Stupet eiusdem…", "timeToRead": 2, "frontmatter": { "title": "Birch in the Roses", "tags": [ "tag" ], "cover": "../static/4b00837366fb63a52fb41969a89d6676/ec749/sutaba-1.jpg", "date": "01/03/2017", "category": "tech", "categoryslug": "tech" } } }, { "node": { "fields": { "slug": "/the-fallen-time", "date": "2001-02-19T15:00:00.000Z" }, "excerpt": "Autolyci eminus retenta Hoc domum solitos veteremque nostrum Lorem markdownum huc suo ara, dubites celeri mihi bicolor. Secuti non? Suo opus…", "timeToRead": 2, "frontmatter": { "title": "The Fallen Time", "tags": [ "test", "something", "tagging" ], "cover": "https://unsplash.it/400/300/?random?TheFallenTime", "date": "01/02/2017", "category": "another one", "categoryslug": "anotherone" } } }, { "node": { "fields": { "slug": "/bold-mage", "date": "2001-01-19T15:00:00.000Z" }, "excerpt": "Quanto et ius coniunctis urbes Sedisti civiliter Lorem markdownum Ixione palus semper peritura barbaque in aureus\nobliquum erigitur…", "timeToRead": 2, "frontmatter": { "title": "Bold Mage", "tags": [ "programming", "stuff", "other" ], "cover": "https://unsplash.it/400/300/?random?BoldMage", "date": "01/01/2017", "category": "tech", "categoryslug": "tech" } } } ] } } }
jun68ykt

2019/01/10 15:09

JSONのサンプル提示、ありがとうございます。categoryプロパティは文字列なので、私の回答のコードでそのままいけると思います。
guest

回答2

0

ベストアンサー

こんにちは。

質問への追記・修正依頼のほうから、 this.props.postEdges のサンプル追記をお願いしており、その回答をまだ頂いていないので、はっきりしたことは言えませんが、render()postList を作るところを、以下のように修正してみるといかがでしょうか? (以下、mapfilter に渡す関数をアロー関数にしています)

修正前

javascript

1const postList = this.getPostList().filter(function (category, index, self) { 2 return self.indexOf(category) === index; 3});

修正後

javascript

1const postListAll = this.getPostList(); 2 3const categoriesAll = postListAll.map(post => post.category); 4 5const postList = postListAll.filter((post, index) => 6 categoriesAll.indexOf(post.category) === index 7);

上記の修正後のロジックを試行するためのサンプルを作成しました。

ただしこのサンプルでは、this.getPostList() の返す配列の要素は、

javascript

1 { category: 'a', categoryslug: 'aaa' }

という形式のもの、つまり、categorycategoryslug はともに文字列であると仮定しています。その点が実際とは異なるかもしれないのでご了承ください。

  

上記のように修正してもうまくいかなかった場合、 props で渡されてくる this.props.postEdges がどのようなものなのかを知りたいので、ご質問に、 this.props.postEdgesのサンプルを追記して頂ければと思います。

以上参考になれば幸いです。

追記

別案を挙げます。以下でもいけるのでは?と思います。

javascript

1const postList = this.getPostList().reduce((list, post) => { 2 const categories = list.map(e => e.category); 3 if (!categories.includes(post.category)) { 4 list.push(post); 5 } 6 return list; 7}, []);

追記2

BAありがとうございます。
上記で追記した reduce を使ったコードは、 some とスプレッド構文を使うことにより、以下のようにさらに短くできました。

javascript

1const postList = this.getPostList().reduce((list, post) => 2 list.some(e => e.category === post.category) ? list : [...list, post], [] 3);

追記3

何度も追記してすみません。蛇足ながら、このコンポーネント Category

カテゴリー一覧を表示するコンポーネント

とのことなので、 this.getPostList() から、重複のない、category の配列を得ることができればよいので、以下でもよいのではと思いました。

javascript

1const categories = [...new Set(this.getPostList().map(e => e.category))];

上記で、要素に重複のない配列 categories が得られるので、これを使って

JSX

1<div className="grid"> 2 {categories.map(category => ( 3 <div className="item"> 4 <p>{category}</p> 5 </div> 6 ))} 7</div>

としてもよいかもしれません。

投稿2019/01/10 13:24

編集2019/01/10 15:41
jun68ykt

総合スコア9058

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

1042limit

2019/01/10 15:04

お世話になります。 ご指摘の通り、文字列がthis.props.postEdgesには文字列が入っておりました。無事動きました。複数のサンプルコードを提示していただき大変勉強になりました。ありがとうございました。
jun68ykt

2019/01/10 15:09

どういたしまして。 > 無事動きました。 とのことでよかったです????
guest

0

既にカテゴリがpostListに入っていた場合、postList.pushする前にreturnしてしまうとか…?

投稿2019/01/10 08:02

dala00

総合スコア441

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問