首页 > 解决方案 > 在 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)
    })
  }

难道我做错了什么?

标签: reactjsecmascript-6

解决方案


如果你还没有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)
    })
}

推荐阅读