简体   繁体   中英

Destructuring object based on another value in redux state

The application has two different tabs, each with identical drop-downs. I am currently saving the 'selectedTab' which is a string, and the 'selectedTabState' which is an object containing both tab1 and tab2, and a string of which selection the user has chosen. I am able to view which tab the user is on, while also saving the drop-down state while switching between tabs. Here is an example of what it looks like.

selectedTab: 'tab1'
selectedTabState: {
  tab1: 'dropdownOptionOne',
  tab2: 'dropdownOptionTwo'
}

What I would like to do is access the selectedTabState of whatever tab the user is on using destructuring. Can I do something like this?

const { selectedStates: { *state of selectedTab* }} = state;

You could use Computed property names with destrcuturing like this

 const state = { selectedTab: 'tab1', selectedTabState: { tab1: 'dropdownOptionOne', tab2: 'dropdownOptionTwo' } } const { selectedTabState: { [state.selectedTab]: value } } = state; console.log(value) 

But, as Brian Le suggested, state.selectedTabState[state.selectedTab] is much more simpler

const state = selectedTab === 'tab1' ? selectedTabState.tab1 : selectedTabState.tab2

这对你有用吗

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM