如何在单行中从单独的变形属性中变形?

问题描述 投票:4回答:1
const { navigation, currentScreen, childIndex } = this.state
const screen = navigation[currentScreen]

我该如何用一行而不是两行写?

javascript reactjs destructuring
1个回答
7
投票

使用{ [currentScreen]: screen },请确保您事先提取了currentScreen

const state = { navigation: { foo: 'val' }, currentScreen: 'foo' };

const { navigation, currentScreen, childIndex, navigation: { [currentScreen]: screen } } = state
console.log(screen);

也就是说,真的很难读。我强烈建议您使用当前版本。仅当您处于actually code-golfing时才对高尔夫球场进行编码,否则最好在几乎所有情况下都针对可读性进行优化。

带有navigation而不是对象的数组的示例:

const state = { navigation: ['val1', 'val2', 'val3'], currentScreen: 1 };

const { navigation, currentScreen, childIndex, navigation: { [currentScreen]: screen } } = state
console.log(screen);
© www.soinside.com 2019 - 2024. All rights reserved.