简体   繁体   中英

‘state’ is not defined no-undef

I use a tutorial to learn React and I got stuck pretty quickly. In the tutorial they use this code:

import React, { Component } from "react";

class Counter extends Component {
  state = {
    count: 0,
  };

  render() {
    return (
      <React.Fragment>
        <span>{this.state.count}</span>

        <button>Increment</button>
      </React.Fragment>
    );
  }
}

export default Counter;

And everything works great.

But in my case, I get this error:

src\components\counter.jsx Line 4:3: 'state' is not defined no-undef Search for the keywords to learn more about each error.

After trying everything, I think it's because of the react version (They use an older version).

So my question is how to fix this error, And what has actually changed between the versions that prevents my code from working. Tnx!

This is an issue not related to react itself but projects created using create-react-app I believe. The ongoing issue is discussed in comments and it has worked for some people by simply re-using the command itself to create a new project but still a comment by maintainers is awaited. So it's not something you did wrong. Chill.

I have been tracking this since yesterday and even tweeted about the same. Some dependency might have been messed up. Probably eslint or one of babel plugins.

The link to the issue - https://github.com/facebook/create-react-app/issues/10598

I ran into the same problem. I was using the wrong version. The documentation below provided me instructions to create a new react app, for the new version. Now I fixed the issue.

https://create-react-app.dev/docs/getting-started/

Put state in constructor:

  constructor(props) {
    super(props);
    this.state = {
       count: 0,
  
  }

Since Constructor is not initialized, the state you are assigning a keyword in React, which is why it's coming as an error.

Fix for your code like this by adding constructor -

constructor(props) {
   super(props);
   this.state = { count: 0 };
}

For more information, refer - Counstructor in React Class Component

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