问题描述
如果符合条件,我目前正在尝试呈现标题和项目列表。例如,我正在使用待办事项应用程序。如果任何待办事项仍标记为完成:false,我想显示一个div,其中包含标题和那些不完整的待办事项列表。我遇到语法错误,并试图找出问题所在(解析错误:意外的令牌,预期为“,”)。任何帮助表示赞赏。
incompletetodos() {
return this.state.todos.filter(todo => !todo.completed)
}
render() {
return (
<div className="todo-list">
{this.incompletetodos().length > 0 && (
<h3>Incomplete</h3>
{this.incompletetodos().map((todo) =>
<div key={todo.id} className="todo">
<button onClick={() => this.handleClick(todo.id)}>Done</button>
<span>{todo.task}</span>
</div>
)}
)}
</div>
)
}
解决方法
您的条件渲染需要返回一个元素。这是React中返回JSX的所有内容的要求-函数,组件,类。
只需将其包裹在一个片段中即可
{this.incompleteTodos().length > 0 && (
<>
<h3>Incomplete</h3>
{this.incompleteTodos().map((todo) =>
<div key={todo.id} className="todo">
<button onClick={() => this.handleClick(todo.id)}>Done</button>
<span>{todo.task}</span>
</div>
)}
</>
)}
请记住,JSX只是调用React.createElement()
的一种精美语法。这是语法错误而不是React的错误,是因为condition && (func() func2())
是无效的语法。意味着this.incompleteTodos().length > 0 && (React.createElement() React.createElement())
也无效。
这是一个正在运行(中断)的示例,该示例显示了这是JavaScript要求,而不仅仅是React。
function a() {
console.log('a');
}
function b() {
console.log('b');
}
true && (a() b());
通过将元素包装在一个片段中,您要做的实际上是将两个函数与另一个函数包装在一起。
function a() {
console.log('a');
}
function b() {
console.log('b');
}
function wrapper() {
a();
b();
}
true && wrapper();
当您将示例转换回React时,它现在只有一个函数调用和有效的JavaScript语法。