[英]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.