我仅在asset.id === collection.masterAssetId
时才尝试渲染组件。在这种情况下,应显示一个星形图标。我正在使用getMasterId
函数来检查这种情况。知道错误在哪里的人吗?
错误:
Parsing error: Unexpected token
70 |
71 | {
> 72 | if(asset.id === this.getMasterId(asset.id)){
| ^
73 | <FaStar />
74 | }}
App.js
import React from 'react';
import './App.css';
import {collections} from "./data.js"
import {assets} from "./data.js"
import {FontAwesome, FaStar} from "react-icons/fa"
class App extends React.Component {
constructor() {
super()
this.state = {
collectionsarr: collections,
assetsarr: assets,
clickedassets: []
}
}
getMasterId(assetnr){
const assetnum = this.state.collectionsarr.find(element => element.masterAssetId === assetnr).masterAssetId
return assetnum
}
render(){
return (
<div className="App">
<h1>Sitecore coding challenge</h1>
<div className="left">
{this.state.collectionsarr.map(element =>
<div key={element.id}>
<p onClick={()=>this.handleAssetsClick(element.id)}>{element.name}</p>
<img src={this.getAssetPath(element.masterAssetId)} alt="pic"/>
<br></br>
</div>
)}
</div>
<div className="right">
{this.state.clickedassets.map(asset =>
<div key={asset.id}>
<img src={require(`./${asset.path}`)} alt="pic"/>
<p>{asset.name}</p>
<p>{asset.id}</p>
<button onClick={() => this.makeMaster(asset.id)}>Make master!</button>
<p>icon "this is the master</p>
{
if(asset.id === this.getMasterId(asset.id)){
<FaStar />
}}
<br></br>
</div>
)}
</div>
</div>
)
}
}
答案 0 :(得分:3)
答案 1 :(得分:0)
您不能在return语句中的内联代码中使用语句。您只能使用表达式。
if语句是一条语句,因此您应将其替换为三元运算符x ? y : z
或条件和运算符&&
之类的表达式:
// ternary
asset.id === this.getMasterId(asset.id) ? <FaStar /> : null
或:
// conditional and
asset.id === this.getMasterId(asset.id) && <FaStar />
React在conditional rendering上有一些很棒的文档。
使用条件和&&
时要小心,好像第一个参数是数字0
(例如list.length && <Component />
)一样,您最终将渲染{{1} },而不是一无所有。
在这种情况下,最好转换为布尔值:
0
或:
Boolean(list.length) && <Component />
答案 2 :(得分:0)
看看是否可行
(asset.id === this.getMasterId(asset.id)) ? <FaStar /> : <></>;
答案 3 :(得分:0)
在render函数的返回代码中,您只能使用表达式(等号右侧允许的内容)。 if
是一个语句,因此是不允许的。 无效不起作用的示例:
const a = if(asset.id === this.getMasterId(asset.id)) return <FaStar />
但是,允许三元表达式。然后看起来像这样:
const a = asset.id === this.getMasterId(asset.id) ? <FaStar /> : null