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);
关于javascript - 如何在一行中从单独的解构属性中解构?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59425500/