javascript - React中设置setState?

查看:155
本文介绍了javascript - React中设置setState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我想在React中调用ajax设置DATA,可是setState时报错?为什么报错信息如下?我该如何修改?
代码打包之类的是好的?可以打印出TEST

index.bundle.js?__VERSION:91 Uncaught TypeError: Cannot read property 'setState' of null

at success (http://localhost:8000/js/index.bundle.js?__VERSION:91:26)
at ajaxSuccess (http://localhost:8000/js/index.bundle.js?__VERSION:1906:31)
at XMLHttpRequest.xhr.onreadystatechange (http://localhost:8000/js/index.bundle.js?__VERSION:2107:99)


var $ = require('./zepto');
var React=require('react');
var ReactDOM=require('react-dom');

var test=document.getElementById('test');

class Test extends React.Component{
    constructor(){
        super();
        this.state = {
            DATA: "",
        };
    }

    componentDidMount(){
        $.ajax({
            url:'https://dev-promotion.chelun.com/GuangzhouCarShow/index?id=1',
            type:'GET',
            success:function(res){
                this.setState({
                    DATA:res
                })
                console.log(res)
            }
        })
    }
    render(){
        return (
            <div>Test</div>
            )
    }
}
ReactDOM.render(<Test/>,test);

解决方案

问题出在this指向上

success函数中,this指向的是如下的配置对象,而不是Test类的实例
{
    url:'https://dev-promotion.chelun.com/GuangzhouCarShow/index?id=1',
    type:'GET',
    success:function(res){
        this.setState({
            DATA:res
        })
        console.log(res)
    }
}
当执行success这个回调函数的时候,该对象实际上是销毁了的,因此会报你上面列出来的`Cannot read property 'setState' of null`错误.

解决方案有很多种,楼上提出的都是可行的,不过我习惯上用箭头函数:

也就是把
success:function(res){
    this.setState({
        DATA:res
    })
    console.log(res)
}
替换成
success: (res) => {
    this.setState({
        DATA:res
    })
    console.log(res)
}    

这篇关于javascript - React中设置setState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆