【发布时间】:2018-10-29 20:52:26
【问题描述】:
您好,由于某种原因,我遇到了一个问题,即图像无法在带有参数的路线上加载。然而,在任何没有参数的路线上,它们都可以正常加载。
所以例如我加载路线'/product/:id';
该路由的那个组件包含这个
class Product extends Component {
constructor(props) {
super(props);
this.state = {
product: null
}
}
componentDidMount() {
this.fetchProduct();
}
fetchProduct() {
const { id } = this.props.match.params;
axios.get(`/api/product/${id}`).then(function (response) {
this.setState({ product: response.data });
}.bind(this));
}
renderProduct() {
let { product } = this.state;
if (!product) {
return false
}
else {
return (
<div className='row'>
<div className='col-md-5'>
<img src={product.main_img} />//this image is not displaying
<h5>{product.title}</h5>
<p>{product.description}</p>
</div>
<div className='col-md-5'>
<Form product={product}/>
</div>
</div>
)
}
}
render() {
return (
<div className='container'>
{this.renderProduct()}
</div>
)
}
}
好的,该产品的所有信息都正确显示,我可以使用 console.log(product.main_img),这是正确的图像。那为什么图片不显示呢?我在另一条路线上有完全相同的图像,没有显示正常的参数。我似乎无法弄清楚。
【问题讨论】:
-
product.main_img记录了什么? -
该图像的正确路径。我将图像本地存储在一个名为 images 的文件夹中,所以它类似于“./images/img-file.png”
-
我以前从来没有遇到过这个问题,并且做过很多次这样的事情。我听说过对 webpack 使用 require,但我认为我不需要,因为就像我说的一样,相同的图像可以在没有参数的其他页面/路由上工作。
-
嗯,图像 URL 相对于当前路径存在问题。我猜“images”文件夹位于站点根目录,并且图像 url 应该是
"/images/img-file.png"。使用product.main_img中的当前URL,浏览器将图像源解析为/api/product/<id>/./images/img-file.png,其规范为/api/product/<id>/images/img-file.png -
@OluwafemiSule 是的,这就是问题所在。将“./images/img-file.png”更改为“/images/img-file.png”即可解决问题。
标签: javascript reactjs image react-router react-router-dom