React-Redux @connect语法错误

时间:2017-08-15 15:20:04

标签: reactjs redux react-redux

我是使用React和Redux的新手,我正在构建一个简单的todos应用程序。我正在使用命令行中的create-react-app工具编写我的应用程序。

问题

我去了其他博客和帖子,其他人提到我缺少一个npm插件来转换装饰器“transform-decorators-legacy”,我将这个添加到我的依赖项和Babel,但我仍然收到相同的错误

Syntax error: Unexpected token (9:0)

   7 | import './App.css';
   8 |
>  9 | @connect((store) => {
     | ^
  10 |   return {
  11 |     user: store.user.user
  12 |   }

我的代码

import React, { Component } from 'react';
import { connect } from 'react-redux';

import Todos from './components/Todos';
import Todo from './components/Todo';

import './App.css';

@connect((store) => {
  return {
    user: store.user.user
  }
})
class App extends Component {
  constructor(){
    super()
    this.state = {
      name: 'Brad',
      todos: [
        {
          id: '001',
          name: 'Take out trash',
          completed: false
        },
        {
          id: '002',
          name: 'Meeting with boss',
          completed: false
        },
        {
          id: '003',
          name: 'Go out to dinner',
          completed: false
        }
      ]
    }
  }
  render() {
    return (
      <div className="App">
        <h1>Hello</h1>
        <Todos name={this.state.name} todos={this.state.todos}/>
        <Todo/>
      </div>
    );
  }
}

export default App;

我的依赖

的package.json

{
  "name": "react-redux-project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.16.2",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-redux": "^5.0.6",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-promise-middleware": "^4.3.0",
    "redux-thunk": "^2.2.0"
  },
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "react-scripts": "1.0.11"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

感谢任何帮助/知识!

3 个答案:

答案 0 :(得分:5)

首先我注意到我同意@ markerikson的答案,使用函数而不是装饰器。

如果您 想要使用装饰器,那么将涉及更多步骤。您已将插件添加到依赖项中,但未告知Babel使用它。

创建React App将Webpack与Babel结合使用,即在react-scripts中。您需要调整Babel配置。 &#34;创建反应应用程序&#34;要做到这一点的方法是从创建React应用程序eject,然后编辑.babelrc - 请参阅https://babeljs.io/docs/plugins/transform-decorators/#usage-via-babelrc-recommended-

答案 1 :(得分:4)

请注意,React和Redux团队通常都不鼓励使用装饰器。相反,在这种情况下,您应该使用connect()作为函数:

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

答案 2 :(得分:2)

试试这样:

const stateMap = (state) => {
    console.log('state', state);
    return {
        //something from state
    };
};

export default connect(stateMap)(App);