Javascript 箭头函数在其封闭函数中没有得到 'this' (React Native)
Javascript arrow function not getting 'this' in its enclosing function (React Native)
这是原代码。但是,'this' 里面的 backHandleFunc 不匹配它的词法范围 componentDidMount
componentDidMount() {
this.props.getStudentList(this.props.course._id)
const backHandleFunc = () => {
const studentStatus = StudentStatus.getStudentStatus(this.state.selected_student)
const aca = ActionCreators.actions
/*Processing checkout and in signature */
const checkinSignature = (this.props.action == aca.OPEN_SIGNATURE && studentStatus == StudentStatus.NOT_IN_NOR_OUT)
/*in one of the three screens, Alert, Covid, Signature (checkout), go back to classDetailScreen */
const inThreeScreens = [aca.OPEN_CONFIRM_ALERT, aca.OPEN_COVID_FORM, aca.OPEN_SIGNATURE].includes(this.props.action)
if (checkinSignature) {
this.props.openCovidForm();
return true;
} else if (inThreeScreens) {
this.props.openClassDetailScreen();
return true;
}
}
this.backHandler = BackHandler.addEventListener(
"hardwareBackPress",
backHandleFunc
);
}
但是一旦我这样做了,
this.backHandler = BackHandler.addEventListener(
"hardwareBackPress",
backHandleFunc.bind(this)
);
它会起作用的。这是为什么?环境是 react native vs code expo 调试器。先感谢您。我也附上调试器信息。
所以问题是,当我在 Expo(nent) 中调试时,Visual Studio 代码中的 React Native Tools 扩展给了我不正确的 'this' 信息。箭头函数中的实际 'this' 与预期的封闭词法范围中的 'this' 相匹配。当我做控制台日志时,我发现这个调试软件的错误,它在箭头函数中给了我 'this' 的正确信息。崩溃是逻辑错误,与箭头功能无关。
这是原代码。但是,'this' 里面的 backHandleFunc 不匹配它的词法范围 componentDidMount
componentDidMount() {
this.props.getStudentList(this.props.course._id)
const backHandleFunc = () => {
const studentStatus = StudentStatus.getStudentStatus(this.state.selected_student)
const aca = ActionCreators.actions
/*Processing checkout and in signature */
const checkinSignature = (this.props.action == aca.OPEN_SIGNATURE && studentStatus == StudentStatus.NOT_IN_NOR_OUT)
/*in one of the three screens, Alert, Covid, Signature (checkout), go back to classDetailScreen */
const inThreeScreens = [aca.OPEN_CONFIRM_ALERT, aca.OPEN_COVID_FORM, aca.OPEN_SIGNATURE].includes(this.props.action)
if (checkinSignature) {
this.props.openCovidForm();
return true;
} else if (inThreeScreens) {
this.props.openClassDetailScreen();
return true;
}
}
this.backHandler = BackHandler.addEventListener(
"hardwareBackPress",
backHandleFunc
);
}
但是一旦我这样做了,
this.backHandler = BackHandler.addEventListener(
"hardwareBackPress",
backHandleFunc.bind(this)
);
它会起作用的。这是为什么?环境是 react native vs code expo 调试器。先感谢您。我也附上调试器信息。
所以问题是,当我在 Expo(nent) 中调试时,Visual Studio 代码中的 React Native Tools 扩展给了我不正确的 'this' 信息。箭头函数中的实际 'this' 与预期的封闭词法范围中的 'this' 相匹配。当我做控制台日志时,我发现这个调试软件的错误,它在箭头函数中给了我 'this' 的正确信息。崩溃是逻辑错误,与箭头功能无关。