我试图声明一个变量“ratingVal”,它在 map 运算符内分配了一个随机的“否”。我想在评级组件中使用该变量并将其显示在屏幕上。但是我收到错误
Parsing error: Unexpected token
在这种情况下声明变量的正确语法是什么?
renderProductsCardsList(products){
return products.map(
(product, i) =>
let ratingVal = Math.floor(Math.random() * 5) + 1
<Rating initialRating={ratingVal} readonly></Rating>
<div>{ratingVal}</div>
)
}
最佳答案
箭头函数中不能有带有隐式返回的声明语句。为此,请使用显式返回语法。此外,您不能从 map 方法中返回多个元素。将它们包裹在<React.Fragment>
内:
renderProductsCardsList(products){
return products.map(
(product, i) => {
let ratingVal = Math.floor(Math.random() * 5) + 1
return (
<React.Fragment>
<Rating initialRating={ratingVal} readonly></Rating>
<div>{ratingVal}</div>
</React.Fragment>
)
})
}
或在分配时对其进行评估
renderProductsCardsList(products){
return products.map(
(product, i) =>
<React.Fragment>
<Rating initialRating={Math.floor(Math.random() * 5) + 1} readonly></Rating>
<div>{ratingVal}</div>
</React.Fragment>
)
}
关于javascript - react 映射运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54751163/