Eslint error: "Must use destructuring state assignment"

Asked

Viewed 796 times

0

Could someone please let me know what I’m doing wrong? The mistake "Must use destructuring state assignment" is in the {this.state.time}.

import React from 'react';

class App extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
     time: '00:00:00',
  };
}

render() {
   const { time } = this.state;
   return (
     <div>
        <h1>
         Hora
          {this.state.time}
         </h1>
     </div>
   );
  }
}

1 answer

5


This error is from a Eslint rule: Enforce consistent Usage of destructuring assignment of props, state, and context (React/destructuring-assignment).

In free translation, this rule serves to have a consistent use of the state (state), of props and the context (context) through the dismantling. To correct the error, you can:

  1. Obey the rule:
render() {
  const { time } = this.state; // Você já tinha essa linha no código
  return (
    <div>
      <h1>
        Hora
        {time} {/* Aqui você usa `time` ao invés de `this.state.time` */}
      </h1>
    </div>
  );
}}

Note: If you try to do const time = this.state.time will have the error again, because will not be accessing via destructuring.

  1. Disable the rule in your file eslintrc or in the Eslint settings in package.json, so the rule will no longer be applied anywhere:
"rules": {
  "react/destructuring-assignment": ['off']
}

This is a rule for consistency in code. Leaving the rule enabled will cause you and your team to access variables in the same way (with de-structuring). Leaving the rule disabled will not bring penalties to your "I’m doing something wrong" code, it just won’t force consistency.

Therefore, any of the above two options are valid and the preference for one or the other part of the developer and the team consensus.

  • 1

    That was exactly the problem. Thank you very much friend!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.