0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSのアロー関数、() と {} の違いを理解する

0
Posted at

結論

// ① 省略記法(returnなし)→ 式をそのまま返す
map((val) => ())

// ② ブロック構文(return必要)→ 処理を書いてから返す
map((val) => { return ; })

=> の後に {} を使うと関数ブロックになるので return が必要。() は式をそのまま返すので不要。

背景

下記のコードを記述したが、UserCardコンポーネントが表示されないし、エラーも起きてない、みたいなケースがあった

import styled from 'styled-components';
import { SearchInput } from '../molecules/SearchInput';
import { UserCard } from '../organisms/user/UserCard';

const users = [...Array(10).keys()].map((val) => {
  return {
    id: val,
    name: `name${val}`,
    image: 'https://images.unsplash.com/photo-1525253086316-d0c936c814f8',
    email: 'sample@gmail.com',
    phone: '080-1234-5678',
    company: {
      name: 'テスト株式会社',
    },
    website: 'hogehoge-example.com',
  };
});

export const Users = () => {
  return (
    <SContainer>
      <h2>ユーザー一覧</h2>
      <SearchInput />
      {users.map((user) => {
        <UserCard key={user.id} user={user} />;
        console.log(user);
      })}
    </SContainer>
  );
};

const SContainer = styled.div`
  display: flex;
  text-align: center;
  flex-direction: column;
  align-items: center;
  padding: 24px;
`;

原因

下記の書き方が間違っていた

export const Users = () => {
  return (
    <SContainer>
      <h2>ユーザー一覧</h2>
      <SearchInput />
      {users.map((user) => {
        <UserCard key={user.id} user={user} />;
        console.log(user);
      })}
    </SContainer>
  );
};

正しくは下記のどっちか

// パターン1
export const Users = () => {
  return (
    <SContainer>
      <h2>ユーザー一覧</h2>
      <SearchInput />
      {users.map((user) => {
        console.log(user);
        return <UserCard key={user.id} user={user} />; // returnをつける
      })}
    </SContainer>
  );
};

// パターン2
export const Users = () => {
  return (
    <SContainer>
      <h2>ユーザー一覧</h2>
      <SearchInput />
      {users.map((user) => ( // カッコを変える
        <UserCard key={user.id} user={user} />
      ))}
    </SContainer>
  );
};

{} を使うと関数ブロックになるので return が必要だった、というのが原因です

{} の中で return を書かないと undefined を返すだけなので、エラーにはならず、ただ何も表示されないという状態だった

{}とは

{}は複数の処理を書きたいなぁという時に使用します

// 関数ブロック → 複数の処理が書ける
map((val) => {
  const name = `name${val}`;  // 処理1
  console.log(name);           // 処理2
  return { id: val, name };    // 明示的に返す
})

{} を使うと「この中は処理を書くエリアですよ」と解釈されるので、値を返したければ自分で return を書く必要がある、ということです

()とは

()を利用すると、式をそのまま返してくれます。なのでreturnは不要です

{users.map((user) => ( // カッコを変える
	<UserCard key={user.id} user={user} />
))}

// 省略記法 → 1つの式をそのまま返すだけ
map((val) => `name${val}`)

感想

このような記事も書いたことありますが、なかなか身に付かんなという感じです

参考

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?