React => Uncaught URIError: This is likely caused by an invalid percent-encoding. Fix

React => Uncaught URIError: This is likely caused by an invalid percent-encoding. Fix

在做react然后遇到了类似

的问题
  Uncaught URIError: This is likely caused by an invalid percent-encoding

我目前正在处理新闻 API,其中一些文章可能包括 %。我的整个应用程序依赖于在 url 中显示新闻文章名称,因为我使用 this.props.match.params.id

我试图在网上搜索解决方案,但在解决这个确切问题时,大多数人都不清楚。

这个问题有简单的解决方法吗?

您需要将 encodeURIComponent() 与您收到的路径一起用作参数: 示例:

const receivedArticleName = encodeURIComponent('Article Name with %');

由于您使用的是 API,一旦您收到它,将您的 URL 变量设置为该 receivedArticleName 即可。

第 1 步转到 /node_modules/history/esm/history.js:87

第 2 步评论此片段

try {
location.pathname = decodeURI(location.pathname);
} catch (e) {
if (e instanceof URIError) {
  throw new URIError('Pathname "' + location.pathname + '" could not be 
  decoded. ' + 'This is likely caused by an invalid percent-encoding.');
} else {
  throw e;
}}

步骤 3 运行 npm 开始

这对我有用。

     function navigate(data: Partial<Saturation>) {
    if (data.name) {
      const checkSyrupForPercentChar = data.name.includes('%')
      const syrupReplacementName = data.name.replace('%', '')

      history.push({
        pathname: `saturation-directory/${data.id}/${urlFormat(
          checkSyrupForPercentChar ? syrupReplacementName : data.name
        )}`,
        state: {
          syrupData: data,
          from: 'syrupDirectory'
        }
      })
    }
  }

重构前的代码:

      function navigate(data: Partial<Saturation>) {
if (data.name) {
  history.push({
    pathname: `saturation-directory/${data.id}/${urlFormat(data.name)}`,
    state: {
      syrupData: data,
      from: 'syrupDirectory'
    }
  })
}

}

要点是我合并的字符串函数以及路径名上的三元运算符。