React.js:原始HTML字符串无法从Node.js中识别为HTML元素 [英] React.js: Raw HTML string does not gets recognized as HTML elements from Node.js
本文介绍了React.js:原始HTML字符串无法从Node.js中识别为HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从node.js发送原始HTML以作出反应.而且成功了.但是,当我尝试呈现它时,它们是作为原始字符串而不是HTML元素呈现的.
I am sending a raw HTML from node.js to react. and It was successful. However, when I try to render it, they are render as raw string as opposed to HTML elements
这是我从前端获取字符串的方式:
This is how I get the string from front-end:
componentDidMount() {
this.callApi()
.then(res => this.setState({ data: res.express}))
.catch(err => console.log(err));
}
callApi = async () => {
const response = await fetch('/myCart');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
react(Simplified)中的render方法如下:
The render method from my react(Simplified) looks like this:
render() {
return (
<div>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to Shopping Center</h1>
</header>
</div>
<div className="row">
{this.state.data}
</div>
</div>
<button type="button" className="btn btn-primary Bottom-right " onClick={(e) => this.handleSubmit(e)}>
My Cart
</button>
</div>
);
}
}
在我的server.js中,我有以下代码处理发布请求:
In my server.js, i have the following code handeling the post request:
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
//DB connections
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
app.get('/myCart', (req, res) => {
var data;
var htmlString ="";
var total = 0;
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("cart");
dbo.collection("items").find().toArray(function(err, result) {
if (err) throw err;
console.log("here")
data = result
for(let item of data){
//console.log("desc: " + item.desc)
//console.log("price: " + item.price)
htmlString += "<div>" + item.desc + "</div>" + "<div>" + item.price + "</div>"
total += item.price
}
console.log("total is" + total)
htmlString +="<div>" + total + "</div>"
console.log(htmlString)
res.send({express: htmlString})
db.close();
});
});
});
为什么不反应将字符串呈现为HTML元素,而是原始字符串?
Why doesn't react render the string as an HTML elements, but rather a raw string?
推荐答案
You may be able to leverage dangerouslySetInnerHtml, like so:
render() {
return (
<div>
<div>
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to Shopping Center</h1>
</header>
</div>
<div
className="row"
dangerouslySetInnerHTML={{__html: this.state.data}}
/>
</div>
<button
type="button"
className="btn btn-primary Bottom-right "
onClick={(e) => this.handleSubmit(e)}
>
My Cart
</button>
</div>
);
}
这篇关于React.js:原始HTML字符串无法从Node.js中识别为HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文