微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

根据密钥更改状态

如何解决根据密钥更改状态

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

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的想法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。