首页 > 解决方案 > 如果组件具有 IIFE,则 React 应用程序无法编译

问题描述

下面是我的组件代码。

function App() {
  !function() {
    console.log("foo")
  }()

  return (
    <div>APP</div>
  )
}

export default App

构建时出现编译错误。

Creating an optimized production build...
Failed to compile.

src\App.js
  Line 2:3:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

Search for the keywords to learn more about each error.


error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

我不明白为什么会出现编译错误。这是有效的 JavaScript 代码。

我可以忽略这个错误吗?


实际上,我用它来使用 useEffect 中的异步功能。

useEffect(() => {
    !async function() {
        await something()
    }()
})

标签: javascriptreactjseslint

解决方案


你能试试这个吗?

function App() {
  true && function() {
    console.log("foo")
  }()
 return !function(){console.log("poo")}
  return (
    <div>APP</div>
  )
}

https://web.archive.org/web/20171201033208/http://benalman.com/news/2010/11/immediately-invoked-function-expression/#iife


推荐阅读