在 _.map 中使用 'this' 属性
Use 'this' property inside _.map
我试图在 _.map 循环中调用 setState 函数,但是循环丢失了 属性 'this',我不能在这上面使用 setState 因为这=未定义
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)});
});
},
这是我的反应函数/\
您需要更改此部分
function(cache)
有
(cache) =>
函数会将它绑定到它的作用域,而箭头函数会在它声明的上下文中绑定到 this。
假设 this 在 class 扩展 React.Component 中,您可以在 class 的构造函数中绑定词法 this:
class YourClass extends React.Component {
constructor(props) {
super(props);
this.cargaDinamica = this.cargaDinamica.bind(this);
}
cargaDinamica() {
your method here
}
这将确保 "this" 指向您方法中的 class 作用域,正如您所希望的那样。
我试图在 _.map 循环中调用 setState 函数,但是循环丢失了 属性 'this',我不能在这上面使用 setState 因为这=未定义
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)});
});
},
这是我的反应函数/\
您需要更改此部分
function(cache)
有
(cache) =>
函数会将它绑定到它的作用域,而箭头函数会在它声明的上下文中绑定到 this。
假设 this 在 class 扩展 React.Component 中,您可以在 class 的构造函数中绑定词法 this:
class YourClass extends React.Component {
constructor(props) {
super(props);
this.cargaDinamica = this.cargaDinamica.bind(this);
}
cargaDinamica() {
your method here
}
这将确保 "this" 指向您方法中的 class 作用域,正如您所希望的那样。