React项目中出现Unexpected template string expression警告的原因排查——编写Product.js时遇到的问题
解决React中"Unexpected template string expression"警告的问题
嘿,这问题我太熟了!你碰到的这个警告完全是因为模板字符串的使用姿势不对~
看你代码里的第9行和第13行:
<a href= '/product/${product._id}'> // Line 9 <a href='/product/${product._id}'> //Line 13
这里你用了单引号来包裹包含${product._id}的字符串,但模板字符串的正确打开方式是用反引号(就是键盘上Tab键上方那个`符号)。单引号里的${}会被当成普通文本,React识别不出这是变量插值,所以就抛出了警告。
只需要把这两行的单引号换成反引号就行,修改后的完整代码如下:
import React from 'react' import Rating from './Rating'; export default function Product(props) { const {product} = props; return ( <div key={product._id} className="card"> <a href={`/product/${product._id}`}> <img className="medium" src={product.image} alt={product.name} /> </a> <div className="card-body"> <a href={`/product/${product._id}`}> <h2>{product.name}</h2> </a> <Rating rating={product.rating} numReviews={product.numReviews} ></Rating> <div className="price">{product.price}lv</div> </div> </div> ) }
简单说,ES6的模板字符串必须用反引号才能让${}语法生效,用来动态插入变量或表达式。换成反引号后,React就能正确解析你要插入的product._id变量了,警告自然就消失啦~
内容的提问来源于stack exchange,提问作者nik_kolev




