【问题标题】:Getting setState is not a function获取 setState 不是函数
【发布时间】:2016-09-19 03:29:48
【问题描述】:

我收到以下错误

//bundle.js:31367 Uncaught TypeError: this.setState is not a 函数//

JSX:

  componentDidMount(){
    $.ajax({
        url:'http://intelligencevillage.wxtui.cn/index.php/Api/HomepageWebview/getHomepageData/area_id/5',
        dataType:'json',
        cache:false,
    }).done(function({data}){
        this.setState({
            lis1:[data.banner]
        })
    })
}

我知道这是某种绑定问题,但我不知道如何解决。任何帮助表示赞赏。

【问题讨论】:

  • 函数({data}) {...}.bind(this)
  • “在这个演示中在哪里添加 .bind(this) 以使其工作” --- 尝试在这里和那里添加它,经过几次尝试你终于会幸运!

标签: ajax reactjs


【解决方案1】:

问题在于函数执行范围。

componentDidMount(){
    $.ajax({
      ...
    }).done(function({data}){
        ///// HERE {this}
        // try console.log(this);
        // you will see there is no`setState`
        this.setState({
            lis1:[data.banner]
        })
    })
}

现在,done 链中的函数,this 仅在函数内部引用。

轻松修复:使用 Fat Arror 函数

componentDidMount(){
    $.ajax({
        url:'',
        dataType:'json',
        cache:false,
    }).done(({data}) => {
        this.setState({
            lis1:[data.banner]
        })
    })
}

【讨论】:

    【解决方案2】:

    问题在于您的情况是 this 不代表正确的上下文。 .done() 中的函数代表了一个单独的上下文,因此您可以

    1。在.done() 之后添加bind(this)

    constructor(props){
        super(props);
        this.state={
    
            lis1:[],
    
        }
    
    }
    componentDidMount(){
        $.ajax({
            url:'',
            dataType:'json',
            cache:false,
        }).done(function({data}){
            this.setState({
                lis1:[data.banner]
            });
        }.bind(this));
    }
    

    2 或者您可以将this 分配给一个单独的变量并使用它。

    constructor(props){
        super(props);
        this.state={
    
            lis1:[],
    
        }
    
    }
    componentDidMount(){
        var self = this;
        $.ajax({
            url:'',
            dataType:'json',
            cache:false,
        }).done(function({data}){
            self.setState({
                lis1:[data.banner]
            })
        })
    }
    

    【讨论】:

    • 再试一次。
    • ".done() 创建一个单独的上下文" --- 不。 “在 .done() 之后添加 bind(this)” --- 不。
    • .bind(this) for this.setState 仍然是错误的。进一步猜测
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    相关资源
    最近更新 更多