Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

javascript - TypeError: Cannot read property 'setState' of undefined

I am trying to setState of a component after a ajax callback receives data from REST api. here's my code for the component constructor

constructor(props) {
    super(props);
    this.state = { posts: [] };
    this.getPosts = this.getPosts.bind(this);
}

Then I have a componentDidMount method that looks like following.

componentDidMount() {
        this.getPosts();
}

Now here's my getPosts function where I am doing the ajax request.

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState( { posts: data } )
        }
    });
}

I am tying to set the State but I am getting the following error.

this.setState is not a function

Not really sure what is causing this. It would be really helpful if someone points me to the right direction. Thanks in advance.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Bind the callback function also so that this inside the callback points to the context of the React Component and not the callback function

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: (data) => {
            this.setState( { posts: data } )
        }
    });
}

or you could use bind like

getPosts = () =>  {
    $.ajax({
        type: 'get',
        url: urlname,
        success: function(data) {
            this.setState({ posts: data })
        }.bind(this)
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...