【问题标题】:URL get's corrupted when React attempts to render an icon当 React 尝试渲染图标时,URL 会损坏
【发布时间】:2021-01-04 17:03:17
【问题描述】:

伙计们,我目前正在开发一个天气应用程序,我在远程位置有一堆图标,我必须渲染它们。 我有一个函数可以访问返回未来 5 天预测的 API。在该数据块中,我还有图标“0d”“1d”等的名称。我试图做的是将图标名称注入我正在点击的API中。当我在控制台记录我创建的链接时,一切看起来都很好,但是当我点击链接时,我得到的是这样的“https://openweathermap.org/img/wn/10d.png%E2%80% 8B”它总是在拨打电话时添加那些尾随字符,我不知道为什么会发生这种情况。

我会把我的代码贴在下面让大家看看

import React from "react";

export const NextDaysWeatherForecast = (props) => {
const { nextDaysWeather } = props;
var auxIndex = 0;
var icon;

return (
    <div>
        {nextDaysWeather.map((days, index) => {
            if (auxIndex < nextDaysWeather.length) {
                let requiredDay = nextDaysWeather[auxIndex];
                auxIndex = auxIndex + 8;
                icon = requiredDay.weather[0].icon;
                let iconAPI = `http://openweathermap.org/img/wn/${icon}.png​`; // I have used string literals to inject the variable
                console.log(iconAPI); // this prints correctly to the console
                return (
                    <div key={index}>
                        <span>def</span>
                        <span>{requiredDay.main.temp}&deg;C</span>
                        <span>{requiredDay.weather[0].description}</span>
                        <img src={iconAPI}></img>// however the image is not displayed
                    </div>
                );
            }
        })}
    </div>
);
};

【问题讨论】:

    标签: javascript reactjs image url


    【解决方案1】:

    在您的 URL 中,在 png 中的 g 之后和反引号之前隐藏了一个零宽度空格。 %E2%80%8B 是零宽度空格 (https://www.fileformat.info/info/unicode/char/200b/index.htm) 的 UTF-8 编码。

    【讨论】:

    • 哇,好的,谢谢。所以我想我可以做 iconAPI.trim() 并删除尾随空格?
    • 最好删除源代码中的零宽度空间。 .trim() 方法不会修剪零宽度空格。
    • 但是在我的源代码中我实际上看不到尾随空格,或者我可以吗?我错过了什么吗?当我检查我的源代码时,我的链接似乎很好。
    • 不,您看不到零宽度空间,因为它的宽度为零。它看起来不存在,但它存在。
    • 我已经尝试过这样的 iconAPI.replace(/\u200B/g, "");但这无济于事
    猜你喜欢
    • 2019-06-16
    • 2021-08-16
    • 1970-01-01
    • 2020-02-09
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    相关资源
    最近更新 更多