【发布时间】:2018-11-05 06:07:34
【问题描述】:
在适应我自己的用例的同时关注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>
我显然遗漏了一些东西,因为我无法弄清楚问题所在:感谢任何帮助。
【问题讨论】:
-
尝试用
? (...)替换你的? {...}。 -
@FMCorz 实际上我认为他只需要删除第 42 行的花括号即可。无论哪种方式,本节中的代码都很难阅读,所以我建议让它更容易阅读,它会使其更易于维护。
标签: ruby-on-rails reactjs api syntax fetch