ReactJS this.state null

前端 未结 5 1204
谎友^
谎友^ 2020-12-28 11:31

Let me preface this by saying I am a novice to ReactJS. I am trying to learn by making a simple site that populates data using React. I have a JSON file that contains link d

相关标签:
5条回答
  • 2020-12-28 12:02

    I had similar issue. In my case it was webpack-dev-server not re-compiling my stuff on the run properly.
    I just restarted the dev server to get it working again.

    0 讨论(0)
  • 2020-12-28 12:07

    This question has already been answered, but I came here by having a problem that can easily happen to anyone.

    I was getting a console.log(this.state) to log null in one of my methods, just because I didn't write:

    this.handleSelect = this.handleSelect.bind(this);

    in my constructor.

    So, if you're getting a null for this.state in one of your methods, check if you have bounded it to your component.

    Cheers!

    Edit (because of @tutiplain's question)

    Why was I getting null for this.state?

    Because I wrote console.log(this.state) in the method which wasn't bounded to my class (my handleSelect method). That caused this to point to some object higher in the object hierarchy (most probably the window object) which doesn't have a property named state. So, by binding my handleSelect method to this, I assured that whenever I write this in that method, it will point to the object in which the method is in.

    I encourage you to read a really good explanation for this here.

    0 讨论(0)
  • 2020-12-28 12:09

    this.state.data is null in your example because setState() is async. Instead you can pass a callback to setState like so:

    loadNavbarJSON: function() {
        $.ajax({
          url: "app/js/configs/navbar.json",
          dataType: 'json',
          success: function(data) {
            console.log(data);
    
            this.setState({data: data}, function(){
              console.log(this.state.data);
            }.bind(this));
    
          }.bind(this),
        });
      }
    

    https://facebook.github.io/react/docs/component-api.html#setstate

    0 讨论(0)
  • 2020-12-28 12:11

    Using ES6, the initial state must be created in your constructor for the React component class, like this:

    constructor(props) {
        super(props)
        this.state ={
        // Set your state here
        }
    }
    

    See this documentation.

    0 讨论(0)
  • 2020-12-28 12:21

    More actual answer, for using ES7+ Classes:

    export class Counter extends React.Component {
      state = { data : [] };
      ...
    }
    

    ES6 Classes (alredy was answered)

    export class Component extends React.Component {
      constructor(props) {
        super(props);
        this.state = { data : [] };
      }
      ...
    }
    
    0 讨论(0)
提交回复
热议问题