[英]React JS: Syntax error: Unexpected token
我一直在使用这段代码
{this.state.display === true ?
this.state.content.map((q) => {
<Content
id={q.id}
key={q.id}
content={q.content}
deleteRow={this.deleteRow()}
/>
})
<AppForm />
在React的return方法中,只要不添加AppForm,一切都可以正常工作,但是当我添加AppForm时,它会给我一个错误:语法错误:意外的令牌。
你能帮我么? 谢谢。
编辑:
如果用户登录(显示为真),我希望同时显示Content和AppForm
这是我完整的渲染代码:
return (
<div>
{this.state.display === true ?
this.state.content.map((q) => {
<Content
id={q.id}
key={q.id}
content={q.content}
deleteRow={this.deleteRow()}
/>
})
<AppForm />
: this.state.display === false ?
<Forms
create={this.createUser}
sign={this.signUser}
/>
: 'Error'
}
</div>
);
您应该发布所有代码。 基于此,我可以猜测两个问题之一:
{this.state.display === true ?
this.state.content.map((q) => {
<Content
id={q.id}
key={q.id}
content={q.content}
deleteRow={this.deleteRow()}
/>
})
<AppForm />
1 : ?
是三元运算符。 那些是为了if this, then do this, else do this
。 对于您正在编写的内联条件,可能更适合使用{this.state.display === true ? &&
{this.state.display === true ? &&
。 如果您要根据条件选择<Content />
或<AppForm />
{this.state.display === true ? (
this.state.content.map((q) => {
<Content
id={q.id}
key={q.id}
content={q.content}
deleteRow={this.deleteRow()}
/>
})
) : (
<AppForm />
)
2:JSX要求所有返回的元素都包装在一个元素中。 通常,这可以通过arbitray <div>
标签完成。
return (
<div>
{this.state.display === true ?
this.state.content.map((q) => {
<Content
id={q.id}
key={q.id}
content={q.content}
deleteRow={this.deleteRow()}
/>
})
<AppForm />
</div>
)
如果有帮助,那就太好了! 如果没有,则需要提供有关代码的更多信息,以帮助我们。
编辑:您不正确地使用三元运算符
return (
<div>
{this.state.display === true ?
this.state.content.map((q) => {
<Content
id={q.id}
key={q.id}
content={q.content}
deleteRow={this.deleteRow()}
/>
})
:
<Forms
create={this.createUser}
sign={this.signUser}
/>
}
<AppForm />
</div>
);
该代码应该工作^
基本上, ?
是隐式的if,else语句。
true ?
console.log('true')
:
console.log('false')
如果声明在左边?
是真的,那么对的左边声明:
评估,否则语句的正确:
被评估。 您不能提供第二个条件,也不能给它两个以上的选择。 如果需要,可以嵌套三元运算符,但语法应始终为condition ? if true do this : if false do this
condition ? if true do this : if false do this
我自由地完全重写了它:
render() {
const {
display
content
} = this.state;
let component = (
<Forms
create={this.createUser}
sign={this.signUser}
/>
);
if(display) {
const mappedContent = content.map((q) => {
return (
<Content
id={q.id}
key={q.id}
content={q.content}
deleteRow={this.deleteRow.bind(this)}
/>
);
})
component = [
mappedContent,
<AppForm
key="AppForm"
/>
];
}
return (
<div>
{component}
</div>
);
}
一些东西:
关于您意外的令牌,如果显示错误,则在测试后您会丢失: {something}
语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.