根据密钥更改状态

Changed State based on the key

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

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..!!

考虑到您正在接收 nextView 作为 home/booth/summary 并且基于此您想要设置相应的键,即 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的想法。