如何在一行中从单独的解构 属性 解构?

How to destructure from a separate destructured property in a single line?

const { navigation, currentScreen, childIndex } = this.state
const screen = navigation[currentScreen]

我怎样才能用一行代码而不是两行来写这个?

使用 { [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);