繁体   English   中英

Typescript / React开始获得很多“variableName未定义”

[英]Typescript / React started getting a lot of “variableName is undefined”

我不确定是什么改变了,也许它甚至与babel有关,但是当我使用像这样的东西时,我开始收到类似UserControler_1错误

UserControler.ts

export function signOut() { console.log("Sign Out") }

Page.tsx

import * as React from "react;
import { signOut } from "./UserControler";
import { TouchableWithoutFeedback, Text } from "react-native";

class Page extends React.Component {
  _signOut = () => signOut()

  render() {
    return (
      <TouchableWithoutFeedback onPress={this._signOut}>
         <Text>Sign Out</Text>
      </TouchableWithoutFeedback>
    )
  }
}

上面的结果是这样的错误

UserControler_1未定义

有时它会更具体地错误,即

找不到变量:signOut

最奇怪的是,如果我将代码更改为类似的东西,它可以正常工作

import * as React from "react;
import { signOut } from "./UserControler";

class Page extends React.Component {    
  render() {
    return (
     <TouchableWithoutFeedback onPress={() => signOut}>
       <Text>Sign Out</Text>
     </TouchableWithoutFeedback>
    )
  }
}

这里很困惑

我的tsconfig

{
  "compilerOptions": {
    "moduleResolution": "node",
    "module": "es6",
    "target": "es6",
    "lib": ["es7"],
    "allowJs": true,
    "checkJs": true,
    "jsx": "react-native",
    "removeComments": true,
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types", "./typings"],
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "exclude": ["./node_modules", "./android", "./ios", "./__tests__", "./dist", "./__mocks__"],
  "include": ["./src"]
}

这构建到dist文件夹中,babel从中获取文件并因此使应用程序工作,我的babelrc

{
  "presets": ["react-native"]
}
<TouchableWithoutFeedback onPress={() => signOut}>

之所以有效,是因为您要返回对上面导入的函数signOut的引用。 需要注意的重要一点是=>无论什么都返回。

 _signOut = () => signOut()

  render() {
    return (
      <TouchableWithoutFeedback onPress={this._signOut}>

不起作用,因为在_signOut中你使用另一个箭头函数,但这次它返回signOut(),然后在那里调用。 你所看到的奇怪之处可能来自这样一个事实:在某些点上,当它击中你的代码并调用函数时,函数可能还没有被导入。

所以解决方案是这样的

 _signOut = () => signOut

  render() {
    return (
      <TouchableWithoutFeedback onPress={this._signOut}>

通过不像以前那样调用函数,一切都按预期工作。

看看如何使用内部箭头功能的优秀解释: https//stackoverflow.com/a/48700540/214347

它似乎是在2.7.1引入的打字稿错误 - 它非常烦人,但好的是升级到2.7.2修复它。 (至少它解决了我遇到的问题)。

更多信息: https//github.com/Microsoft/TypeScript/issues/21478

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM