gpt4 book ai didi

javascript - 如何避免在 ES6 : const that = this when scope nested in React 中创建 'this' 的引用

转载 作者:行者123 更新时间:2023-11-30 08:19:12 25 4
gpt4 key购买 nike

我正在阅读 air-bnb javascript 样式指南,它说不应该这样做:

23.5 不要保存对此的引用。使用箭头函数或 Function#bind。

// bad
function foo() {
const self = this;
return function () {
console.log(self);
};
}

// bad
function foo() {
const that = this;
return function () {
console.log(that);
};
}

// good
function foo() {
return () => {
console.log(this);
};
}

我已经做了一些研究,并在 stackoverflow 中找到了两个答案,但其中一个被接受的答案是无法规避:

ES6 avoid that/self

另一个建议使用绑定(bind),但它建议使用生成器函数。

Nested reference to `this` in ES6 classes

我正在构建一个 ReactJS 应用程序,我需要从 firebase Promise 中访问 setState。

   saveSessionToDB = () => {
const that = this;
db.collection("sessions")
.add({
props: MyProps
})
.then(function(docRef) {
console.log("Session written with ID: ", docRef.id);
that.setState({ sessionID: docRef.id });
})
.catch(function(error) {
console.error("Error adding document: ", error);
that.setState({ sessionError: error });
});
}

我试过了

const {setState} = this;

然后

setState({sessionID:docRef.id});

但是我得到一个错误。

我尝试在构造函数中绑定(bind) saveSessionToDB 无济于事,即使它是一个箭头函数。

是否有另一种方法可以做到这一点,或者我是否应该接受有时我仍然必须编写 const that = this?

最佳答案

thencatch 也必须使用箭头函数:

saveSessionToDB = () => {
db.collection("sessions")
.add({ props: MyProps })
.then((docRef) => {
console.log("Session written with ID: ", docRef.id);
this.setState({ sessionID: docRef.id });
})
.catch((error) => {
console.error("Error adding document: ", error);
this.setState({ sessionError: error });
});
}

箭头函数之所以有用,是因为它们没有自己的this上下文(或arguments),所以它们采用了 this 来自他们的外部词汇环境。这就是为什么您可以在箭头函数中使用组件的 this

关于javascript - 如何避免在 ES6 : const that = this when scope nested in React 中创建 'this' 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56867493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com