2017-06-04 139 views
1

我無法使裝飾器(如@observable和@computed)在我的項目中工作。MobX裝飾器無法正常工作

這是我的文件。

的package.json:

{ 
    "name": "heroku-react", 
    "version": "0.1.0", 
    "private": true, 
    "dependencies": { 
    "babel-plugin-syntax-decorators": "^6.13.0", 
    "mobx": "^3.1.11", 
    "mobx-react": "^4.2.1", 
    "react": "^15.5.4", 
    "react-dom": "^15.5.4" 
    }, 
    "devDependencies": { 
    "babel-plugin-transform-decorators-legacy": "^1.3.4", 
    "babel-preset-stage-1": "^6.24.1", 
    "react-scripts": "1.0.7" 
    }, 
    "scripts": { 
    "start": "react-scripts start", 
    "build": "react-scripts build", 
    "test": "react-scripts test --env=jsdom", 
    "eject": "react-scripts eject" 
    } 
} 

App.js:

import React, { Component } from 'react'; 
import './App.css'; 
import GameBoard from './components/game-board'; 
import { inject, observer } from 'mobx-react'; 

class App extends Component { 
    render() { 
    return (
     <div className="App"> 
     <div className="App-header"> 
     </div> 
     <GameBoard /> 
     </div> 
    ); 
    } 
} 

export default App; 

.babelrc:

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

當我加入@Observer裝飾像這樣(@Observer類應用擴展組件{...})在我的類聲明之前我收到此錯誤:

Failed to compile 
./src/App.js 
Syntax error: Unexpected token (7:0) 

    5 | import { inject, observer } from 'mobx-react'; 
    6 | 
> 7 | @observer class App extends Component { 
    |^
    8 | render() { 
    9 |  return (
    10 |  <div className="App"> 

回答

2

看起來像你使用create-react-app並沒有使eject。爲了使用裝飾器,你應該做到這一點。或者使用custom-react-scripts作爲替代。

0

當您使用create-react-app時,安裝mobx的正確方法如下;

  1. create-react-app ExampleApp
  2. npm run eject
  3. npm install --saveDev babel-plugin-transform-decorators-legacy
  4. 更新您的.babelrc文件,因爲它是現在(與變換裝飾遺留)
  5. npm install --save mobx mobx-react

這應該做的招。