我正在创建一个React组件,该组件将显示Redux存储中存储的一些文本。但是在显示该文本之前,我想检查内容并根据找到的内容进行更改(通过正则表达式)。
如果在文本中找到RegEx匹配项,我们将向数据库发出异步获取请求以获取一些文本。我想用从数据库中获取的文本替换与正则表达式匹配的文本。
但是,当我实现这样的代码时:
import React from "react";
import ApolloClient from "apollo-boost";
import gql from "graphql-tag";
import { connect } from "react-redux";
import * as coolActions from "../actions/coolActions";
class MyComponent extends React.Component {
parseMarkup(body) {
var some_regex = /{{(?<type>thing)(?:\s-val\s)(?<val>.+?)(?:}})/m;
var match;
var ml;
while ((match = some_regex.exec(body)) !== null) {
ml = match[0]; //the entire match, including {{}}
var an_id = match[2]; //an ID found in the RegEx match
const client = new ApolloClient({
uri: "https://a_database.org/graphql" //Apollo Server address
});
var fetchedText = client
.query({
query: gql`
{
fetch_by_id(ID: "${an_id}"){Body}
}
`
})
.then(result => {
var text = result.data.fetch_by_id.Body;
console.log("Text fetched from database: " + text);
return text;
});
body = body.replace(ml, fetchedText);
}
return body;
}
render() {
return (
<div>
<span style={{ whiteSpace: "pre-line" }}>
{this.parseMarkup(this.props.template.Body)}
</span>
</div>
);
}
}
const mapStateToProps = state => ({
template: state.cool.template
});
export default connect(
mapStateToProps,
{ ...coolActions }
)(MyComponent);
呈现的文本为“ [对象承诺]” ,而不是从服务器成功获取的实际文本。从服务器获取的文本将在控制台中打印。我认为问题是由于我将“ body = body.replace()”行放置在Promise链的.then()部分之外,导致Promise被打印,因为尚未解决。
但是,当我在.then()部分中放置“ body = body.replace()”行时,会发生无限循环:
parseMarkup(body) {
var some_regex = /{{(?<type>thing)(?:\s-val\s)(?<val>.+?)(?:}})/m;
var match;
var ml;
while ((match = some_regex.exec(body)) !== null) {
ml = match[0]; //the entire match, including {{}}
var an_id = match[2]; //an ID found in the RegEx match
const client = new ApolloClient({
uri: "https://a_database.org/graphql" //Apollo Server address
});
client
.query({
query: gql`
{
fetch_by_id(ID: "${an_id}"){Body}
}
`
})
.then(result => {
var text = result.data.fetch_by_id.Body;
console.log("Text fetched from database: " + text);
body = body.replace(ml, text);
return text;
});
}
return body;
}
运行此命令时,while循环将无限循环。我注意到正则表达式缺少“ / g”全局标志,并且读到它的缺失会导致这样的循环。不幸的是,当我像这样在正则表达式中添加“ / g”时:
var some_regex = /{{(?<type>thing)(?:\s-val\s)(?<val>.+?)(?:}})/gm;
该文本似乎不再被替换。我不确定下一步该怎么做。任何见解都将不胜感激。