如何导航到react-router中带有百分号的路径?

问题描述 投票:0回答:2

我正在尝试导航到网址中可能包含百分比 (%) 符号的页面。例如

"www.domain.com/edit/name%"

if (some condition is met then redirect) {
  let encodedString = encodeURIComponent(this.state.identifier);

  console.log(encodedString);

  return <Redirect push to={`/edit/${encodedString}`} />
}

在我们重定向到的组件中:

if (params && params.identifier) {
  this.setState({
    identifier: decodeURI(params.identifier)
  });
}

console.log();
我可以清楚地看到
encodedString
,前提是
this.state.identifier
name%
name%25
。但是,当满足重定向条件时,我立即收到此错误
URIError: Pathname "/edit/name%" could not be decoded. This is likely caused by an invalid percent-encoding.

如果

/:identifier
有百分号,有没有办法重定向到 uri?

javascript reactjs routes react-router react-router-dom
2个回答
0
投票

这里的问题是

decodeURI
方法会认为这是编码的开始,当没有任何后续内容时,就会抛出错误。尝试以下片段:

const decodedParam = "text%";
const encodedParam = encodeURIComponent(decodedParam);

const encodedUrl = `/edit/${encodedParam}`;
const decodedUrl = decodeURIComponent(encodedUrl);

console.log({ encodedUrl, decodedUrl });

上面的代码片段使用了

decodeURIComponent
方法。您可以在这里查看两者之间的区别。


-1
投票

尝试编码两次并解决...

© www.soinside.com 2019 - 2024. All rights reserved.