我正试图使'this'的值永远不会被不确定:
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
class App extends Component {
constructor() {
super();
this.state = {
name: "React",
toChange: "needs changing"
};
this.next = this.next.bind(this); // is this needed?
}
next() {
console.log("this one: ", this);
const testFn = () => {
console.log("this two: ", this);
};
if (true) {
testFn();
console.log('this 3', this);
/*
this.setState{(
toChange: "changed!" // this errors - unknown reason why
)}*/
const testFnTwo = function() {
console.log('this 4', this);// how to make 'this' be the same value as in the upper scope?
[1].forEach(function() {
console.log('this 5: ', this); // how to make 'this' be the same value as in the upper scope?
});
}();
}
}
render() {
return <div>{this.next()}</div>;
}
}
render(<App />, document.getElementById("root"));
演示:https://stackblitz.com/edit/react-wf2dkz-单击右下角的“控制台”
如何在testFnTwo
中设置'this'的值及其内部的forEach函数以在外部执行上下文中匹配相同的'this'值?
此测试的另一个主要目标是更改toChange
的状态(根据此注释代码):
/*
this.setState{(
toChange: "changed!" // this errors - unknown reason why
)}
*/
有人知道为什么这也行不通吗?我已经看到它可以在网络上其他地方的演示中使用,但是由于某些原因,我会收到此错误:
Error in index.js (30:19)
'types' can only be used in a .ts file.
感谢您的帮助。
此1、2、3将是“所需的此”。但是this 4&5位于function
内,并且this
将为rebound。要防止这种行为,请使用arrow function:
const testFnTwo = (() => {
console.log('this 4', this);
[1].forEach(() => {
console.log('this 5: ', this);
});
})();
并且setState
调用中出现错误的原因是您的方括号是错误的。应该是({
而不是{(
:
this.setState({
toChange: "changed!"
});
您可以将next()
函数本身更改为箭头函数,并将内部范围更改为箭头函数,以便为this
关键字获得正确的范围。
this.setState
中还有一个错误,因为括号放错了位置,应该像这样,
this.setState({
toChange: "changed!" // this errors - unknown reason why
})
因此组件看起来像,
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
class App extends Component {
constructor() {
super();
this.state = {
name: "React",
toChange: "needs changing"
};
}
next = () => {
console.log("this one: ", this);
const testFn = () => {
console.log("this two: ", this);
};
if (true) {
testFn();
console.log('this 3', this);
this.setState({
toChange: "changed!" // this errors - unknown reason why
})
const testFnTwo = () => {
console.log('this 4', this);// how to make 'this' be the same value as in the upper scope?
[1].forEach(() => {
console.log('this 5: ', this); // how to make 'this' be the same value as in the upper scope?
});
};
testFnTwo();
}
}
render() {
return <div>{this.next()}</div>;
}
}
render(<App />, document.getElementById("root"));
此外,在{this.next()}
中像这样调用render
方法也不是最佳实践,因为它将无限次调用next()
函数。