[英]ReactJS unexpected token in return statement
如果上下文變量設置為 none,我不想返回任何內容。
但是我在 if 上得到了意外的標記?
return (
<AppContext.Consumer>
{context => (
if(context.objects[0] !== "none")
return;
<ul>
{context.objects.map((object, key) => {
return <li key={key}>{object.type}
//--- snip ----
編輯:整個(工作)組件代碼是這樣的
const ObjectList = (props) => {
return (
<AppContext.Consumer>
{context => (
<ul>
{context.objects.map((object, key) => {
return <li key={key}>{object.type}
<Button
key={key}
style={{backgroundColor: "red"}}
onClick={() => context.deleteObject(key)}
>
x
</Button>
</li>
})}
</ul>
)}
</AppContext.Consumer>
);
}
但這總是呈現 1 li 元素,因為對象在上下文提供程序中初始化時將“none”作為元素:
const [objects, setObjects] = useState(['none']);
我希望僅在對象數組中存在“無”以外的其他內容時才繪制列表。
使用return null
而不是return
。
有關更多信息,請參閱此問題: Is it possible to return empty in react render function?
使用大括號作為箭頭函數的主體:
{context => {
當使用括號時,括號內必須是一個語句,該語句的返回值成為函數的返回值。
您需要{}
return (
<AppContext.Consumer>
{context => ({ // <- this
if(context.objects[0] !== "none")
return;
return ( // <-and this
<ul>
{context.objects.map((object, key) => {
return <li key={key}>{object.type}
//--- snip ----
如果您只想返回其中的內容,則 As ()是簡寫。 沒有邏輯。 但是如果你添加if
那么它會返回它並且 JXS 會說unexpected token。
最好的方法是
{context && context.objects[0] !== "none" && (<ul>
{context.objects.map((object, key) => (<li key={key} {object.type}>{object.data}</li></ul>)})}
如果您不想從組件呈現任何內容,則應返回 null。 像這樣
return (null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.