reactjs - 在 React 中,为什么我不能使用嵌套的箭头函数……虽然正常的函数似乎可以工作?
问题描述
以下不起作用。
generateFakeAnswer = () => {
getRealAnswer = (state) => {
return state.valueOne + state.valueTwo + state.valueThree;
}
this.setState({
fakeAnswer: Math.floor(Math.random() * 10) + getRealAnswer(this.state)
})
}
但以下确实有效。
generateFakeAnswer = () => {
function getRealAnswer(state) {
return state.valueOne + state.valueTwo + state.valueThree;
}
this.setState({
fakeAnswer: Math.floor(Math.random() * 10) + getRealAnswer(this.state)
})
}
难道我做错了什么?
解决方案
如果你还没有let getRealAnswer
你应该在你的function
.
严格模式使得不可能意外创建全局变量。在正常的 JavaScript 中,在赋值中输入错误的变量会在全局对象上创建一个新属性并继续“工作”(尽管将来可能会失败:在现代 JavaScript 中很可能)。赋值会意外创建全局变量,而在严格模式下会抛出错误:
// Assuming no global variable mistypeVariable exists
mistypeVariable = 17; // this line throws a ReferenceError due to the
// misspelling of variable
所以你的功能应该是这样的:
generateFakeAnswer = () => {
const getRealAnswer = (state) => {
return state.valueOne + state.valueTwo + state.valueThree;
}
this.setState({
fakeAnswer: Math.floor(Math.random() * 10) + getRealAnswer(this.state)
})
}
推荐阅读
- r - 如何在 R 中的数据框中生成新行,以将汇总的成功/失败计数转换为单独的 1/0(逻辑回归)?
- python - Networkx 常见邻居未正确过滤,未返回正确的邻居列表
- observable - 无法订阅 BehaviorSubject
- python - 具有 multi_line 的多个图例条目,具有单独的交互性
- pytorch - PyTorch - TypeError:在 DataLoader 工作进程 0 中捕获 TypeError
- javascript - 内容安全策略未按预期工作
- flutter - 如何从 Flutter Beamer 中的 2 个不同位置导航到同一页面
- flutter - 如果我在 iPad 上购买了订阅,但再也没有打开或卸载应用程序并仅通过 Android 使用应用程序,会发生什么情况
- intellij-idea - Intellij - 找不到要前往的声明
- powershell - PowerShell:更改数组中对象的值