You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React编译失败:Parsing error unexpected token,第20行代码调试求助

解决React编译错误:Parsing error: Unexpected token(第20行)

Hey there! Let's figure out why you're hitting this parsing error in your AddProject.js component. That "Unexpected token" message on line 20 almost always means there's a syntax mix-up somewhere—most likely a misplaced curly brace or code in the wrong scope.

Looking at your code snippet:

18 | e.preventDefault();
19 | }
> 20 | if(this.refs.title.value === ''){
| ^
21 | alert('Title is required');
22 | } else {
23 | this.setState({newProject:{

The problem here is that line 19's closing } is ending your submit handler function, and then you're trying to run an if statement directly in the class's top-level scope. JavaScript classes don't allow executable code like if statements outside of methods—they can only contain method definitions, class fields, etc.

Fix Steps:

  • Move the entire if-else block inside your submit handler: Make sure the if check lives within the function that handles the form submit, right after e.preventDefault();.
  • Check for unclosed braces/parentheses: Your setState call on line 23 starts an object but doesn't close it—make sure you finish defining the newProject object and close all curly braces properly.

Here's what the corrected code structure should look like:

class AddProject extends Component {
  // Your component state and other methods here...

  handleSubmit(e) {
    e.preventDefault();

    // This if-else block stays inside the handler function
    if(this.refs.title.value === ''){
      alert('Title is required');
    } else {
      this.setState({
        newProject: {
          title: this.refs.title.value,
          // Add any other project properties you need here
        }
      });
    }
  }

  render() {
    // Your render JSX here...
  }
}

Quick side note: While this.refs works in older React versions, the official docs now recommend using createRef() or callback refs for better control. But since you're following Brad's tutorial, let's get the syntax sorted first—you can refactor to modern refs later if you want!

内容的提问来源于stack exchange,提问作者Drew Norman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:52:38