[英]Unexpected token error in React app
好的,所以我遇到了一个我一直在跟着Udacity课程一起学习的问题。 问题在于整个课程应用程序都包含在一个文件中,并且越来越难以深入查找问题所在。
在某个时候,出现了一个错误,我认为这是一种语法错误,在该错误中我已经添加或错过了括号或类似内容,但是我找不到它发生的地方。
我认为它特定于下面的App
组件,但看不到我做错了什么。
VS Code中突出显示的语法指向下面的行,其中const
未突出显示,就像在代码的其他区域一样。
const Context = React.createContext()
class App extends React.Component {
const Context = React.createContext()
class ConnectedApp extends React.Component {
render() {
return (
<Context.Consumer>
{(store) => (
<App store={store}/>
)}
</Context.Consumer>
)
}
}
class Provider extends React.Component {
render() {
<Context.Provider value={this.props.store}>
{ this.props.children }
</Context.Provider>
}
}
componentDidMount () {
const { store } = this.props
store.dispatch(handleIitialData())
store.subscribe( () => this.forceUpdate())
}
render() {
const { store } = this.props
const { todos, goals, loading } = store.getState()
if(loading) { return <h3>Loading</h3> }
return(
<div>
< Todos todos={todos} store={this.props.store} />
< Goals goals={goals} store={this.props.store} />
</div>
)
}
}
Error
babel.min.js:27 Uncaught SyntaxError: Inline Babel script: Unexpected token (108:18)
106 | class App extends React.Component {
107 |
> 108 | const Context = React.createContext()
| ^
109 |
110 | class ConnectedApp extends React.Component {
111 | render() {
at r.l.raise (babel.min.js:27)
at r.c.unexpected (babel.min.js:27)
at r.c.expect (babel.min.js:27)
at r.m.parseMethod (babel.min.js:27)
at r.parseClassMethod (babel.min.js:28)
at r.m.parseClassBody (babel.min.js:27)
at r.m.parseClass (babel.min.js:27)
at r.m.parseStatement (babel.min.js:27)
at r.parseStatement (babel.min.js:27)
at r.m.parseBlockBody (babel.min.js:27)
这是因为您试图在该类中使用的语法不在babel配置中,也不在您的引擎(节点/浏览器)支持下(而这只是该类public field proposal的提议 )。
您应该宁愿在babel中添加对该语法的支持( 第3阶段 ),但要知道该语法有可能无法作为该语言的最终功能通过。
或在类外部(或在类的构造函数内部)声明Context常量,然后使用此上下文访问它。
示例(来自官方文档,但已根据您的代码进行了修改):
// the Context is created outside App
const Context = React.createContext();
// Also ConnectedApp and Provider are OUTSIDE App (The console doesnt complain now, but it will after you fix the one with const)
class Provider extends React.Component {
render() {
<Context.Provider value={this.props.store}>
{ this.props.children }
</Context.Provider>
}
}
class App extends React.Component {
componentDidMount () {
const { store } = this.props
store.dispatch(handleIitialData())
store.subscribe( () => this.forceUpdate())
}
render() {
const { store } = this.props
const { todos, goals, loading } = store.getState()
if(loading) { return <h3>Loading</h3> }
return(
<div>
< Todos todos={todos} store={this.props.store} />
< Goals goals={goals} store={this.props.store} />
</div>
)
}
}
// ConnectedApp goes after App since it uses App internally
class ConnectedApp extends React.Component {
render() {
return (
<Context.Consumer>
{(store) => (
<App store={store}/>
)}
</Context.Consumer>
)
}
}
您的代码中还有其他React概念错误,但是由于您正在学习一门课程,我想目前这是故意的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.