React.js:为什么状态未定义?

时间:2017-10-04 14:43:22

标签: javascript node.js reactjs promise

我需要在脚本的每次迭代中写入状态信息。如何正确地做到这一点?

    getPageLink(i) {
        if(i > 0){
            console.log(this.state.res) // aaa
            new Promise((resolve, reject) => {
                request(this.props.catalogLinks[i], function (error, response, html) {
                    if (!error && response.statusCode == 200) {
                        var $ = cheerio.load(html);
                        $('.post__title_link').each(function (i, element) {
                            console.log(this.state.res) // undefined
                        });
                        resolve("result");
                    } else {
                        console.log('sss', this.state.res) // undefined
                        reject("result");
                    }
                });
            }).then(
                result => {
                    this.getPageLink(--i)
                },
                error => {
                    this.getPageLink(--i)
                }
            );
        }
    }

现在在控制台中:

  

AAA

     

bundle.js:53444未捕获的TypeError:无法读取未定义的属性'res'

如何解决错误?

full code

2 个答案:

答案 0 :(得分:0)

this在回调中被覆盖。您应该将其值放入另一个变量中:

var that = this;

然后从那时开始使用that

    getPageLink(i) {
        if(i > 0){
            console.log(this.state.res) 
            var that = this;
            new Promise((resolve, reject) => {
                request(this.props.catalogLinks[i], function (error, response, html) {
                    if (!error && response.statusCode == 200) {
                        var $ = cheerio.load(html);
                        $('.post__title_link').each(function (i, element) {
                            console.log(that.state.res)
                        });
                        resolve("result");
                    } else {
                        console.log('sss', that.state.res)
                        reject("result");
                    }
                });
            }).then(
                result => {
                    this.getPageLink(--i)
                },
                error => {
                    this.getPageLink(--i)
                }
            );
        }
    }

答案 1 :(得分:0)

在定义回调函数时,您必须使用箭头符号() => {}

request(this.props.catalogLinks[i], (error, response, html) => {
       if (!error && response.statusCode == 200) {
          var $ = cheerio.load(html);
          $('.post__title_link').each((i, element) => {
              console.log(this.state.res) // will be defined
          });
          resolve("result");
       } else {
          console.log('sss', this.state.res) // will be defined
          reject("result");
       }
});