【发布时间】:2016-12-19 20:34:34
【问题描述】:
我用我的 ajax 请求结果填充的数组不会出现在我的 react 组件无序列表中。
当我对数组执行 console.log 时,我得到:
[] 0 : “事业”
1 : “技术职业中学”
2 : “新西兰职业生涯”
3 : “退伍军人职业 200”
4 : “北区健康职业高中”
5 : “芭比的职业生涯”
6 : “爱德华·肯尼迪健康职业学院”
7 : “伦敦大学职业小组”
8 : “职业顾问”
9 : "职业咨询服务"
长度 : 10
原型 : 数组[0]
当我在我的 react 组件中调用这个数组时,它不会呈现。下面是我的代码。
HTML
<div id="content"></div>
JS
// array that the titles will be loaded into
var response = [];
$.ajax({
// request type ( GET or POST )
type: "GET",
// the URL to which the request is sent
url: "https://en.wikipedia.org/w/api.php?",
// data to be sent to the server
data: {
action: "query",
format: "json",
list: "search",
srsearch: "careers",
srwhat: "text",
srprop: "timestamp",
continue: "",
},
// The type of data that you're expecting back from the server
dataType: "jsonp",
crossDomain: true,
// Function to be called if the request succeeds
success: function (jsondata) {
for (var i = 0; i < jsondata.query.search.length; i++) {
//console.log( jsondata.query.search[i].title );
//pushes each result into the array named list
response.push(jsondata.query.search[i].title);
}
},
});
console.log(response);
var App = React.createClass({
render: function () {
//var title = list;
return (
<div>
<h1>Hello World</h1>
<p>The world is full of oppurtunity</p>
<ul>
<li>{response[0]}</li>
<li>Freedom</li>
<li>Lozve</li>
<li>Money</li>
</ul>
</div>
);
},
});
ReactDOM.render(<App />, document.getElementById("content"));
这是我的代码笔的链接,我的所有代码都在其中,http://codepen.io/vhall_io/pen/vKQrQN/。我将 response[0] 插入到第一个 li 标记中,它不会呈现。请帮我渲染一下。
【问题讨论】:
-
您在 ajax 调用返回之前调用了
render。把ReactDOM.render放在你的for循环之后 -
感谢@azium 这确实有效。
-
没问题。你知道为什么以前的方法不行吗?
-
我相信是这样,据我了解,无序列表是在 ajax 调用返回请求之前创建的。 ul 元素一旦创建就无法修改。
-
UI 元素当然可以使用
this.state和this.setState进行更改
标签: javascript arrays ajax reactjs jsx