【问题标题】:mobx + react unexpected tokenmobx + 反应意外令牌
【发布时间】:2017-04-29 13:02:11
【问题描述】:

所以我从https://facebook.github.io/react/blog/2016/07/22/create-apps-with-no-configuration.html 创建了一个无需配置即可做出反应的应用

我安装了 mobx 和 mobx-react ,但在@symb 之前仍然显示意外令牌的错误。

是否需要添加其他内容,或者我当前的配置有误?:(

package.json

"devDependencies": {
"react-scripts": "0.8.4",
"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"
},
"dependencies": {
"autobind-decorator": "^1.3.4",
"classnames": "^2.2.5",
"lodash": "^4.15.0",
"mobx": "^2.5.1",
"mobx-react": "^3.5.5",
"react": "^15.3.1",
"react-dom": "^15.3.1",
"validator": "^5.6.0"
 },

.babelrc

{
  "presets": ["es2015", "stage-0", "react"],
  "plugins": [
      "transform-decorators-legacy",
      "transform-class-properties"
  ]
}

还有代码

import React, { Component } from 'react';
import { action, observable } from 'mobx'
import {observer} from 'mobx-react';


class App {
    @observer cake = [];
}

export default new App();

【问题讨论】:

  • @observer 是用于 React 组件的装饰器。如果你想要可观察的数据,你应该使用装饰器@observable
  • 无论我使用什么,当我使用@symb 时,它就会停在那里。所以我认为mobx没有正确安装
  • 哦,我误会了。我认为这是因为 create-react-app 根本不支持装饰器(@)。我不认为 MobX 是这里的罪魁祸首。你可以试试mobx-react-boilerplate
  • 谢谢,我会试试看;)

标签: reactjs mobx mobx-react


【解决方案1】:

create-react-app 不支持装饰器 (@)。你可以eject create-react-app 自己添加它,从头开始设置你自己的环境,或者使用mobx-react-boilerplate 之类的东西作为你的起点。

我个人使用react-app-rewiredmobx extension 取得了巨大成功。

【讨论】:

【解决方案2】:

在运行 npm run eject 后你丢失了包(因为 create-react-app 不支持装饰器)。

运行npm install --save-dev babel-plugin-transform-decorators-legacy babel-plugin-transform-class-properties

然后将以下 Babel 配置添加到你的 package.json 中

"babel": {
  "plugins": [
    "transform-decorators-legacy"
  ],
  "presets": [
    "react-app"
  ]
},

【讨论】:

  • 我认为你也应该将 transform-class-properties 添加到 Babel 插件数组中。
【解决方案3】:

您可以使用提供的不使用装饰器的语法(herehere)。

这是一个使用您提供的 App 类代码的示例:

import React, { Component } from 'react';
import { action, extendObservable } from 'mobx'
import {observer} from 'mobx-react';


class App {
  constructor() {
    extendObservable(this, {
      cake = [],
    }); 
  }
}

export default new App();

【讨论】:

    猜你喜欢
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多