我遇到了将django render参数作为服务器响应传递并使用react组件获取它然后将其发送到html的问题。
以下是Django代码:
def view_personal_details (request):
personal_detail_json = personal_details.objects.all()
personal_detail = serializers.serialize('json', personal_detail_json)
return render (request, "webFiles/reactOutput.html", {'personal_detail': personal_detail})
以下是反应代码,用于获取通过django响应发送的'personal_detail':
var categories = []; //{ "model": "buglockerApp.authentication_details", "pk": 1, "fields": { "userid": "001", "password": "rajiv@247", "sec_que": "Pet Name", "sec_ans": "Jerry" } }];
var App = _react2.default.createClass({
displayName: 'App',
getInitialState: function getInitialState() {
return {
data: null
};
},
componentDidMount: function componentDidMount() {
var self = this;
//var http = require("http");
var REQUEST_URL = "/viewPersonalDetails";
// var request = http.get(REQUEST_URL, function (response) {
// console.log ("react response" + JSON.stringify(response));
// var buffer = "",
// data;
// console.log("categories :" + JSON.stringify(categories));
// response.on("data", function (chunk) {
// buffer += chunk;
// });
// response.on("end", function (err) {
// self.setState({
// categories: buffer
// });
// console.log('buffer: ' + buffer);
// console.log('categories: ' + JSON.stringify(categories));
// });
// });
fetch(REQUEST_URL, {
method: 'get',
dataType: 'json',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) =>
{
return response.json() // << This is the problem
})
.then((responseData) => { // responseData = undefined
return responseData;
})
.then((data) => {
console.log(data);
});
},
render: function render() {
return _react2.default.createElement(
'div',
null,
_react2.default.createElement(_griddleReact2.default, { results: categories, tableClassName: 'table', showFilter: true, showSettings: true, columns: [] })
);
}
});
_reactDom2.default.render(_react2.default.createElement(App, null), document.getElementById('app'));
以下是反应组件将呈现输出的HTML内容:
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<title>React First App</title>
{% load static %}
</head>
<body>
Django Direct Output: <br />
{{ personal_detail }}
------------------------ <br />
React Output: <br />
<div id = "app"></div>
<script src = "{% static 'js/reactResponseNoDefaultJson.js' %}"></script>
</body>
</html>
{{personal_detail}} 部分(在上面的HTML内容中)直接从Django中提供了正确的json值,但是html中的下面部分(即app div和下面的javascript)没有返回反应的内容。 reactResponseNoDefaultJson.js'是缩小的反应js。
答案 0 :(得分:0)