React中函数内的setState,this未定义

8

我刚开始学习React,所以我肯定缺少一些基础知识。我在尝试在一个调用fetch的函数的返回中设置state时,得到了undefined,因此无法读取属性'setState'。请问我做错了什么?需要注意的是,我从onClick中调用MyAction,并且响应数据是正确的。

var ItemComponent = React.createClass({

    getInitialState: function() {
        return {
            the_message: "call that API!"
        };
    },

    doFetch: function() {
        var obj = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        };
        return fetch('http://localhost:1337/site/test', obj)
            .then(function(response) {
                return response.json();
            }).then(function(data) {
                return data;
            }).catch((error) => {
                console.error(error);
            });
    },

    MyAction: function() {
        this.doFetch().then(function(response){
            this.setState({
                the_message: response.message
            });
        })
    },

    render: function() {
        return (
            <div>
                <div>{this.props.title}</div><br></br>
                <div>{this.props.price}</div><br></br>
                <div onClick={this.MyAction}>{this.props.qty}</div>
            </div>
        );
    }
});

可能是[“this”关键字如何工作?]的重复问题(https://dev59.com/zHA75IYBdhLWcg3wv70j)。 - Andy Ray
3个回答

11

使用箭头函数 (() => {}),它将保持最后的作用域(this)不变。

MyAction: function(){
    this.doFetch().then((response) => {
        this.setState({
            the_message: response.message
        });
    });
},

函数组件怎么样?那么语法会是什么呢? - Amrit

8

你的内部 Promise 解析函数不会有 this 上下文。修复方法之一:

MyAction: function(){
    this.doFetch().then(function(response){
        this.setState({
            the_message: response.message
        });
    }.bind(this))
},

关于此问题的更多信息,请访问这个 StackOverflow 问题


完美,你修复了第二个问题。我不确定你在第一个问题中提出的建议是什么,因为我的代码没有改变?无论如何,一旦允许我接受你的答案(5分钟),我就会接受它。顺便问一下,我应该真的使用ES6语法吗?在开始一些教程后,我认为这种语法已经过时了。 - edencorbin
双重糟糕,我刚才假设你正在使用ES6类,第一个更新是无关紧要的。请将您的问题标记为重复。 - Andy Ray

3
一个简单的.bind(this)就可以解决这个问题:
render: function() {
return (
<div>
<div>{this.props.title}</div><br></br>
<div>{this.props.price}</div><br></br>
<div onClick={this.MyAction.bind(this)}>{this.props.qty}</div>
</div>
);

通过添加.bind(this),您可以使作用域保持在函数内部。


2
您每次渲染时都会使用此方法创建一个新函数。最好将处理程序绑定到构造函数中,或在类内部创建箭头函数。 - Isaac Pak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接