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 (
            

Test

) } } ReactDOM.render(,test);
PHPz
PHPz

学习是最好的投资!

全部回复(3)
阿神

用箭头函数来绑定 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`

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

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