【问题标题】:Cannot find name in Typescript with MobX使用 MobX 在 Typescript 中找不到名称
【发布时间】:2019-02-06 18:28:04
【问题描述】:

我创建了简单的 MobX 商店:

import { observable, action, computed } from "mobx"

interface UserInterface {
  login: string
  email: string
  password: string
}

class User {

  @observable users: UserInterface[] = []

  @action addUser = (newUser: any) => {
    this.users.push(newUser)
  }

  @action logMe = () => {
    console.log("MobX works!");
  }

  @computed get userCount() {
    return this.users.length
  }
}

export const UserStore = new User()

这是使用来自此存储的数据的组件的开始:

import withStyles, { WithStyles } from "@material-ui/core/styles/withStyles"
import { inject, observer } from "mobx-react"
import { UserStore } from "../../../stores/user-store"

interface RegisterFormProps extends WithStyles<typeof RegisterFormStyles> {
  userStore?: UserStore
}
@inject("userStore")
@observer
class LoginForm extends React.Component<RegisterFormProps> {

我在userStore?: UserStore 部分有一个 tslint 错误。它抛出错误:Type error: Cannot find name 'UserStore'. TS2304。这个类的路径是正确的。如果我将类型从 UserStore 更改为 any 它可以工作,但我想避免使用 any 类型。

@编辑。解决方案是在 MobX 存储文件的末尾包含以下行:

const UserStore = new User();
export { UserStore }

【问题讨论】:

    标签: reactjs typescript mobx mobx-react


    【解决方案1】:

    你试过了吗?

    const UserStore = new User();
    export { UserStore }
    

    【讨论】:

      【解决方案2】:

      export const UserStore = new User() 表示您正在导出变量UserStore,并且变量不能用作类型(但类可以)。你必须导出类UserStore在接口userStore?: User中使用它

      【讨论】:

      • 不起作用。我收到错误this.props.userStore.addUser is not a function 如何正确导出?
      • 好的,但是错误Type error: Cannot find name 'UserStore'. TS2304 消失了吗?您能否在定义和调用addUser 方法的地方也显示部分代码?
      • addUser() 方法在 store 中声明,看第一段。
      • 是的,你说得对。但是你确定你在Provider组件中也有这样的东西:&lt;Provider userStore = {userStore}&gt; where userStore = new User();
      • 我建议 export class User ...import { Class } from ... 而不是导出默认值。
      猜你喜欢
      • 2016-05-23
      • 2016-12-04
      • 1970-01-01
      • 2019-10-28
      • 1970-01-01
      • 2016-11-05
      • 2018-08-29
      • 1970-01-01
      • 2016-01-24
      相关资源
      最近更新 更多