【问题标题】:Images not loading on route with params but works on routes without params图像未在带有参数的路线上加载,但在没有参数的路线上有效
【发布时间】: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/&lt;id&gt;/./images/img-file.png,其规范为/api/product/&lt;id&gt;/images/img-file.png
  • @OluwafemiSule 是的,这就是问题所在。将“./images/img-file.png”更改为“/images/img-file.png”即可解决问题。

标签: javascript reactjs image react-router react-router-dom


【解决方案1】:

我遇到了同样的问题,我修复了它,但将所有指向图像的链接更改为以斜杠“/”开头,然后是目录名而不是“./”或只是目录名。

【讨论】:

  • 您阅读问题下方的 cmets 了吗?如果是这样,您的回答为这个问题带来了哪些新信息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
相关资源
最近更新 更多