[英]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.