简体   繁体   中英

Error in declaring a variable inside the component class and outside the render function to use it inside the render function in react

in the code bellow when I declare the varable characters via destructuring

const { characters } = this.state;

I get a Unexpected token error.

 import React, { Component } from "react"; import Table from "./Table"; class App extends Component { state = { characters: [ { name: "Charlie", job: "Janitor" }, { name: "Mac", job: "Bouncer" }, { name: "Dee", job: "Aspring actress" }, { name: "Dennis", job: "Bartender" } ] }; removeCharacter = index => { const { characters } = this.state; this.setState({ characters: characters.filter((character, i) => { return i !== index; }) }); }; const { characters } = this.state; render() { return ( <React.Fragment> <div className="App"> <h1>Hello, React!</h1> </div> <div className="container"> <Table characterData={characters} removeCharacter={this.removeCharacter} /> </div> </React.Fragment> ); } } export default App; 

here is a sandbox of the code: sandbox with the error, look at the app.js file

and when I put the declaration inside the render function there is no problem, look at the correct code sandbox.

Also when I create a variable, outside of the render function (of the App.js file), without const or let for example:

x=1;

It works fine when I use it inside the render function as this.x, but when I declare it with let,const or var it throws me an Unexpected token error.

How do you explain that behaviour?

You have destructed characters outside the render method.

import React, { Component } from "react";
import Table from "./Table";
class App extends Component {
  state = {
    characters: [
      {
        name: "Charlie",
        job: "Janitor"
      },
      {
        name: "Mac",
        job: "Bouncer"
      },
      {
        name: "Dee",
        job: "Aspring actress"
      },
      {
        name: "Dennis",
        job: "Bartender"
      }
    ]
  };
  removeCharacter = index => {
    const { characters } = this.state;

    this.setState({
      characters: characters.filter((character, i) => {
        return i !== index;
      })
    });
  };
  render() {
    const { characters } = this.state;
    return (
      <React.Fragment>
        <div className="App">
          <h1>Hello, React!</h1>
        </div>

        <div className="container">
          <Table
            characterData={characters}
            removeCharacter={this.removeCharacter}
          />
        </div>
      </React.Fragment>
    );
  }
}

export default App;

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