根据密钥更改状态

问题描述

我想根据传递的值更改布尔状态

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      formElement: {
        home: true,booth: false,summary: false
      },};
  }

  buttonClickHandler(event,nextView) {  //nextView == summary
    // nextView == summary then summary would be true and booth would be flase and home would flase too
  }
}

Here based on nextView all state value should be reserved.

Thanks in advance..!!

解决方法

考虑到您正在接收home / booth / summary的nextView,并基于此您要设置相应的键,即formElement [nextView] = true,对于其他键,即formElement [!nextView] = false。

您可以尝试以下操作:

buttonClickHandler (event,nextView) {  
  const { formElement } = this.state;
  Object.keys(formElement).forEach(key => {
     this.setState({
       formElement: {
         ...formElement,[key]: key === nextView  // here will check if the current key matches nextView
       }
     });
  });
}

如果可以的话,我认为您可以使用更简单的状态变量。 喜欢

this.state = {
      formElement: 'home'
};

然后

 buttonClickHandler (event,nextView) {  
      this.setState({
        formElement: nextView
      });
   }

这只是https://en.wikipedia.org/wiki/KISS_principle的想法。