React语法错误:意外的令牌,预期为“,”

时间:2018-11-05 06:07:35

标签: ruby-on-rails reactjs api syntax fetch

在适应自己的用例的同时遵循https://blog.heroku.com/a-rock-solid-modern-web-stack

当我如下更新我的app.js文件时:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor () {
    super()
    this.state = {}
    this.getWords = this.getWords.bind(this)
    this.getWord = this.getWord.bind(this)
  }

  componentDidMount () {
    this.getWords()
  }

  fetch (endpoint) {
    return window.fetch(endpoint)
      .then(response => response.json())
      .catch(error => console.log(error))
  }

  getWords () {
    this.fetch('/api/words')
      .then(words => {
        if (words.length) {
          this.setState({words: words})
          this.getWord(words[0].id)
        } else {
          this.setState({words: []})
        }
      })
  }

  getWord (id) {
    this.fetch(`/api/words/${id}`)
      .then(word => this.setState({word: word}))
  }

  render () {
    let {words, word} = this.state
    return words
    ? {words && words.length
      ? {Object.keys(words).map((key) => {
          return <a href={word && word.id === words[key].id} onClick={() => this.getWord(words[key].id)}>
                  {words[key].term}
                </a>
        })}
      : <p>No word found.</p>
    }
    : <p>Loading...</p>
  }
}

export default App;

我收到以下错误:

./src/App.js
Syntax error: Unexpected token, expected "," (42:14)

  40 |     let {words, word} = this.state
  41 |     return words
> 42 |     ? {words && words.length
     |              ^
  43 |       ? {Object.keys(words).map((key) => {
  44 |           return <a href={word && word.id === words[key].id} onClick={() => this.getWord(words[key].id)}>
  45 |                   {words[key].term}

尽管页面布局的结构少了一些,但逻辑对我来说却是相同的。

我想念什么?

更新:我对代码进行了如下编辑:

  render () {
    let {words, word} = this.state
    return words
    ? (words && words.length)
      ? (Object.keys(words).map((key) => {
          return <a href={word && word.id === words[key].id} onClick={() => this.getWord(words[key].id)}>
                  (words[key].term)
                </a>
        })
      : return
        <p>No words found.</p>
    }
    : <p>Loading...</p>
  }

现在出现以下错误:

./src/App.js
Syntax error: Unexpected token (48:9)

  46 |                 </a>
  47 |         })
> 48 |       : return
     |         ^
  49 |         <p>No words found.</p>
  50 |     }
  51 |     : <p>Loading...</p>

我显然缺少一些东西,因为我无法弄清楚问题出在哪里:任何帮助都将得到感谢。

1 个答案:

答案 0 :(得分:2)

好像有一个额外的花括号,逻辑似乎有点偏离。试试这个:

mlxtend