我创建了简单的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 }
你试试这个?
const UserStore = new User();
export { UserStore }
export const UserStore = new User()
意味着要导出变量UserStore
和可变不能使用类型(但类可以)。必须导出类UserStore
使用它在接口userStore?: User