3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ReactでObject.keysとmapを使ってobject of objectsを展開する

Last updated at Posted at 2020-02-03

before(冗長)


type news = {
    content: string;
}

interface Props {
    1: news;
    2: news;
    3: news;
}

const NewsItems: React.FC<Props> = (props) => {
  return (
    <div>
        <div>
            {props[1].content}
        </div>
        <div>
            {props[2].content}
        </div>
        <div>
            {props[3].content}
        </div>
    </div>
  )
);

冗長ッ!!引くほど冗長ッ!!!

after


interface Props {
    [order: number] : {
        content: string;
    }
}

const NewsItems: React.FC<Props> = (props) => {
  return (
    <div>
        {Object.keys(props.newses).map(order => {
            return (
                <div key={order}>
                    {props.newses[parseInt(order).content]}
                </div>
            );
        )}}
    </div>
  )
);

point

  • interfaceでブラケットを使用する

[キーの名前 : キーの型指定] : バリューの型指定
という風に書く事で1,2,3などと書かなくてよくなる
また、キーの型指定ができることで、mapでまわすときのkeyの型が決まるため、その後のprops.newses[ここの中]に怒られずに入れることができる

  • Object.keysの返り値である配列の要素は文字列になることに注意

Object.keysの返り値はこの場合["1", "2", "3"]となってしまうので、parseIntを忘れずに。
もともとキーがstringだったらこんなことしなくて良いです。
(これで1時間ほど悩んでしまった。)

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?