首页 > this作用域问题

this作用域问题

如何不用这种写法;理想的写法是this.setState({

....

})

可能是我没有描述清楚,我不想用这种学法而已,这样多了一个变量,我觉得很不舒服。我尝试了先把 setState 赋值到变量里,底下用那个变量。这样就不要this了。但是没有成功,所以求一种更简练的方法。


想保留this,那只能用arrow-function了,代码这样改:

componentDidMount: function() {
    var n = 1;
    axios({
        method: 'get',
        url: this.props.url,
        params: {
            page: n
        }
    })
        .then(response => {
            this.setState({
                data: response.data
            });
        })
        .catch(error => {
            console.log(error);
        });
}

then那里用箭头函数

then((response) => {
this.setState...
}

在回调函数里 this 的指向有变化,所以用变量that缓存下外面的this


把匿名函数改成es6的箭头函数,箭头函数没有this引用,所以不会覆盖外面的this


因为js的函数会创建新的作用域,新函数中的this如果没有特殊指定的话是指向全局的。


用ES6标准中的箭头函数。

((response) => this.setData())...
【热门文章】
【热门文章】