【问题标题】:Use 'this' property inside _.map [duplicate]在_.map中使用'this'属性[重复]
【发布时间】:2017-05-29 18:59:00
【问题描述】:

我正在尝试在 _.map 循环内调用 setState 函数,但循环丢失了属性“this”,我无法在此上使用 setState,因为 this=undefined

  cargaDinamica(){

    _.map(this.state.redis, function(cache){
      obj.url = 'http://localhost:7000/viewlogredis';
      ServiceOS(obj)
      .then(retorno => {
        console.log("aaaa", this);
        view = retorno;
         this.setState({log : view});
      })
      .catch(err => {throw new Error(err)});


    obj = {url : 'http://localhost:7000' + cache.WebService,
            IPRedis: cache.IPDBMaster,
            WebService: cache.WebService,
            log : log};
    console.log("CARGA: ", obj);
     ServiceOS(obj)
       .then(function(carga) {
         console.log('CHEGOU AQUI');
         console.log("OK");
       })
       .catch(err => {throw new Error(err)});


    });

  },

这是我的反应函数/\

【问题讨论】:

  • 通过有界上下文传递函数(){}.bind(this)

标签: javascript node.js reactjs ecmascript-6 underscore.js


【解决方案1】:

假设 this 在扩展 React.Component 的类中,你可以在类的构造函数中绑定词法 this:

class YourClass extends React.Component {
  constructor(props) {
    super(props);
    this.cargaDinamica = this.cargaDinamica.bind(this);
  }

  cargaDinamica() {
    your method here
  }

这将确保“this”指向您方法内的类范围,如您所愿。

【讨论】:

    【解决方案2】:

    你需要改变这部分

    function(cache)
    

    (cache) =>
    

    函数会将其绑定到其作用域,而箭头函数将绑定到声明它的上下文中的 this。

    【讨论】:

    • 注意:这是 ES6 语法,可能会在旧浏览器中中断,您可以建议 .bind() 代替。
    • 如果我没记错的话,React 会被转译成 ES5,所以不用担心。
    • 我知道,如果有人正在寻找类似的问题,但只使用 underscorejs 而没有反应,就在这里发布一些信息。
    • 谢谢!它工作 100%
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 2014-04-18
    • 2019-05-17
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多