React代码可运行但提示Expected an assignment or function call,未使用表达式错误原因咨询
Hey there! Let's break down why you're seeing that Expected an assignment or function call error in your React code, and how to fix it.
The Root Cause
Looking at your onKeyPress handler:
e =>{(e.key ==='Enter' ? this.addTodo(e.target.value):null) }
The issue lies in how you've structured the arrow function. When you wrap an arrow function's body in {}, JavaScript expects the content to be executable statements (like assignments, function calls, or condition blocks). But here, you've written a standalone ternary expression—when the key isn't Enter, it returns null, but this result is never used (no assignment, no function call that consumes it). ESLint (or your code linter) flags this as a "useless expression" because it doesn't do anything meaningful in statement context.
Fixes to Try
You have two clean ways to resolve this:
1. Use Implicit Return (Remove the Curly Braces)
Arrow functions skip the need for return and curly braces when you're only returning a single expression. This turns your ternary into a valid return value instead of an unused statement:
<input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e => e.key === 'Enter' ? this.addTodo(e.target.value) : undefined} />
I swapped null for undefined here—it's more semantically accurate for "no action taken", but either works.
2. Use an if Statement (More Readable)
If you prefer keeping curly braces for clarity, replace the ternary with an explicit condition check. This turns the logic into a proper statement that the linter won't flag:
<input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e => { if (e.key === 'Enter') { this.addTodo(e.target.value); } }} />
This is my recommended approach—it's easier to read at a glance, especially if you ever need to add more logic later.
内容的提问来源于stack exchange,提问作者DCR

