Ad

Functions Breaking In React Native Tutorial

- 1 answer

I'm trying out React Native and functions of React components like getInitialState and componentDidMount are breaking. For instance, I tried:

getInitialState: function() {
    return {
      movies: null,
    };
  },

which broke.

When I put the es6 equivalent, which is:

constructor(props) {
    super(props);
    this.state = {
      movies: null,
    };
}

the program ran fine. What would be the best way to approach this so I'd be able to use the React functions mentioned in the tutorial instead of translating them to es6?

Thanks!

Ad

Answer

I cannot see your code to see how your components were created, but I think I know what's going on here.

If you set up your components as a class:

class MyComponent extends React.Component {

}

You can only use a constructor to set up your initial state:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: null,
    };
  }

  render() {
    return <View />
  }
}

If you set up your component using React.createClass, you can only set up your initial state using getInitialState:

var MyComponent = React.createClass({
  getInitalState: function() {
    return {
      movies: null,
    }
  },
  render: function() {
    return <View />
  }
})

All of the other lifecycle methods should work the same. Note that if you are using class, putting a comma after each function in your class will break your application.

For example, this will break:

class MyComponent extends React.Component {
  componentDidMount() {
    console.log("mounted")
  }, // <- No comma necessary
  render() {
    return <View />
  }
}

This works:

class MyComponent extends React.Component {
  componentDidMount() {
    console.log("mounted")
  }
  render() {
    return <View />
  }
}

The opposite is the case when using React.createClass. You need to separate your function with commas:

This will break:

var MyComponent = React.createClass({
  componentDidMount: function() {
     console.log("mounted")
  } // <- Needs a comma here.
  render: function() {
    return <View />
  }
})

This works:

var MyComponent = React.createClass({
  componentDidMount: function() {
     console.log("mounted")
  },
  render: function() {
    return <View />
  }
})
Ad
source: stackoverflow.com
Ad