Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 使用正则表达式设置状态_Regex_Reactjs - Fatal编程技术网

Regex 使用正则表达式设置状态

Regex 使用正则表达式设置状态,regex,reactjs,Regex,Reactjs,我将64位编码图像的值设置为对象{photo:“/9j/…Q==”},但我希望使用正则表达式仅获取“”中的值。不仅如此,我还有这个值作为状态的值(this.state.profilePhoto=Object{photo:“/9j/…Q==”})。我试图使用正则表达式过滤掉我想要的实际值,并用新的、正确的值替换状态。这就是我所拥有的,但它似乎不起作用,因为它返回的是实际的正则表达式 const regex = /(.*)/; const photo = //some get request thi

我将64位编码图像的值设置为
对象{photo:“/9j/…Q==”}
,但我希望使用正则表达式仅获取“”中的值。不仅如此,我还有这个值作为状态的值(
this.state.profilePhoto=Object{photo:“/9j/…Q==”}
)。我试图使用正则表达式过滤掉我想要的实际值,并用新的、正确的值替换状态。这就是我所拥有的,但它似乎不起作用,因为它返回的是实际的正则表达式

const regex = /(.*)/;
const photo = //some get request
this.setState({ profilePhoto: photo});
this.setState({profilePhoto: regex});

当我将profilePhoto的状态输出记录到控制台时,我得到
/([“'))(?:(?=(\\?)\2。)*?\1/;
而不是引号内的数字。

在代码段中,您实际上没有将正则表达式应用于
photo
的值。如果
photo
是一个字符串,则需要将上面的内容修改为:

const regex = /(.*)/;
const photo = //some get request
const filteredValue = photo.match(regex)
this.setState({ profilePhoto: filteredValue });
也就是说,在您的问题中,photo似乎只是一个对象,您只想在其中包含键
photo
的值?如果您只想让photo成为字符串而不是对象,您可以使用:

const photo = //some get request
// Pull the photo key from the photo Object, renaming to photoString
const { photo: photoString } = photo
this.setState({ profilePhoto: photoString });
参考资料:


  • @JacobN我在使用Reacton作为你的第二个建议,我仍然需要过滤掉引号,对吗?另外,match返回一个数组,我不希望在第二个建议中,你会在控制台中出现一个带引号的字符串yes,但它不是值的一部分。例如,如果你运行
    const substring=photoString.substring(1,yourString.length-1);
    您只需删除“/”和“=”字符。Match返回一个匹配数组,是的。在这种情况下,您将有一个匹配。
    const filteredValue=photo.Match(regex)[0]