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
ifcheck lives within the function that handles the form submit, right aftere.preventDefault();. - Check for unclosed braces/parentheses: Your
setStatecall on line 23 starts an object but doesn't close it—make sure you finish defining thenewProjectobject 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

