javascript - React中设置setState?
PHPz
PHPz 2017-04-11 09:22:57
[JavaScript讨论组]

我想在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 (
            <p>Test</p>
            )
    }
}
ReactDOM.render(<Test/>,test);
PHPz
PHPz

学习是最好的投资!

全部回复(5)
天蓬老师

问题出在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)
}    
PHP中文网
$.ajax({
            url:'https://dev-promotion.chelun.com/GuangzhouCarShow/index?id=1',
            type:'GET',
            success:function(res){
                this.setState({
                    DATA:res
                })
                console.log(res)
            }
        }.bind(this));
阿神

用箭头函数来绑定 this。

success: (res) => {
  this.setState({
    DATA:res
  })
  console.log(res)
}
大家讲道理

this指向问题,可以用es6箭头函数或者bind

success: (res)=> {
    this.setState({
        DATA:res
    })
}
阿神
  1. 用箭头函数,可以自动绑定this

  2. function(){}.bind(this)

  3. 最古老的,用that替换`this`

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号