[英]Setting HTML inside React from AJAX response
I am trying to get some data and set a page to be the result 我正在尝试获取一些数据并将页面设置为结果
function getData() {
$.ajax({
url:"http://localhost:8080/",
type:'GET',
dataType: 'html',
success: function(data){
console.log(data);
$('.App').html(data);
}
});
}
class App extends Component {
render() {
getData()
return (
<div className="App">This worked</div>
);
}
}
export default App;
This is the response being printed out: 这是正在打印的响应:
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no"><meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico"><title>React App</title><link href="/static/css/main.c17080f1.css" rel="stylesheet"></head><body><div id="root"><div class="App" data-reactroot=""><header class="App-header"><img src="logo.svg" class="App-logo" alt="logo"/><h1 class="App-title">Welcome to React</h1></header><div></div></div></div><script type="text/javascript" src="/static/js/main.d1b4ad06.js"></script></body></html>
When the page loads, it flashes the correct HTML for a second, then I get this error: 页面加载后,它会闪烁正确的HTML一秒钟,然后出现此错误:
VM11047:1 Uncaught SyntaxError: Unexpected token <
What am I doing wrong? 我究竟做错了什么?
You could use react's dangerouslySetInnerHTML prop, more info here https://reactjs.org/docs/dom-elements.html 您可以使用react的危险的SetInnerHTML道具,更多信息请参见https://reactjs.org/docs/dom-elements.html
or the safer way to handle is to return a json response and create components to display that returned data 或更安全的处理方式是返回json响应并创建组件以显示返回的数据
there is also an interesting article on why not to mix jquery dom manipulation and react. 还有一篇有趣的文章,介绍为什么不混合使用jQuery dom操作和做出反应。 http://tech.oyster.com/using-react-and-jquery-together/
http://tech.oyster.com/using-react-and-jquery-together/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.