简体   繁体   中英

How to define state in react components?

I am quite new to React and wonder how this should work:

class App extends Component {
> 4 |   state = {
    |         ^
  5 |     bands: [],
  6 |     concerts: []
  7 |   }

here the error message:

ERROR in ./src/App.js
Module build failed: SyntaxError: Unexpected token (4:8)

Edit (the whole component):

import React, { Component } from 'react'

class App extends Component {
  state = {
    bands: [],
    concerts: []
  }
  render() {
    return <div>hei</div>
  }
}

export default App

Some solution to this?

If the code is really as shown, you're trying to use a language feature ("class fields") that isn't in the language yet, it's still a stage 3 proposal . You need to ensure whatever transpiler you're using handles transpiling that.

If you don't want to use class fields, define your state property in a constructor:

class App extends Component {
  constructor(...args) {
    super(...args);
    this.state = {
      bands: [],
      concerts: []
    };
  }
  render() {
    return <div>hei</div>
  }
}

One option would be to put the state inside your constructor:

class App extends Component {
  constructor(props) { 
    super(props)
    this.state = {
      bands: [],
      concerts: []
    };
  }
  render() {
    // Here you can access to this.state
    return <div>hei</div>
  }
}

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