简体   繁体   中英

Reactjs eslint rule must use destructuring state assignment

class MyDrawer extends Component {
  const modalOpen = this.state;

  render() {
    return (
      <div>
        <Drawer
          modal
          open={this.state.modalOpen} // <-- this line show error [eslint] Must use destructuring state assignment (react/destructuring-assignment)
          onClose={() => this.setState({ modalOpen: false })}
        >
        </Drawer>
      </div>
    );
  }
}

export default MyDrawer;

I tried change the line to be const { modalOpen } = this.state; but now Failed to compile.

How can i follow the rule and edit my code to be Compiled successfully?

const is in wrong place. Only class members can be declared inside class MyDrawer extends Component {...} , and const is not allowed there. Destructuring assignment should reside inside a function where a variable should be available:

  render() {
    const { modalOpen } = this.state;

    return (
      <div>
        <Drawer
          modal
          open={modalOpen}
          onClose={() => this.setState({ modalOpen: false })}
        >
        </Drawer>
      </div>
    );
  }

Try this:

class MyDrawer extends Component {
  const { modalOpen } = this.state; //fixed

  render() {
    return (
      <div>
        <Drawer
          modal
          open={ modalOpen } // fixed
          onClose={() => this.setState({ modalOpen: false })}
        >
        </Drawer>
      </div>
    );
  }
}

export default MyDrawer;

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