ES6, Javascript. Объявите const, неопределенный в назначении деструктурирования - PullRequest
0 голосов
/ 08 мая 2018
const Profile = () => (
  <Data data={CURRENT_PLAYER_DATA}>
    {({
      data: {
        currentPlayer: { playerProfile }
      }
    }) => <div>{playerProfile && playerProfile.name}</div>}
  </Data>
);

С кодом выше я получил: playerProfile of undefined!

const Profile = () => (
  <Data data={CURRENT_PLAYER_DATA}>
    {({ data: { currentPlayer: { playerProfile = {} } = {} } = {} }) => (
      <div>{playerProfile && playerProfile.name}</div>
    )}
  </Data>
);

С кодом выше это работает, но я не знаю почему.

А также мне нужно избегать чего-то вроде:

playerProfile && playerProfile.name

Как хорошо понять этот поток?

1 Ответ

0 голосов
/ 08 мая 2018

Ваше currentPlayer свойство равно undefined, что означает, что вы по существу делаете

var playerProfile = data.currentPlayer.playerProfile;

Что сломается, поскольку data.currentPlayer не существует. (undefined)

Во втором примере вы создаете значение по умолчанию для currentPlayer, что означает, что currentPlayer, если undefined будет {}

...