我的 previous question 中的问题最近已解决,现在产生了一个新问题,其中我的数组中的值未显示在渲染的下拉列表中。使用我在上一个问题中给出的答案,用正确的键填充列表,但我对数组中的值感兴趣,而不是键值。我在下面列出了修改后的渲染方法,以及我的类原型(prototype)从应用程序中的另一个组件接收到的类数据类型的示例。
编辑: 我发现this source这正是我想做的,但是当尝试他们的代码时,我在控制台中收到一个错误,指出“e.map 不是函数”。我也在下面发布了我尝试过的代码。
编辑 2:为了不讲太多细节,我在组件最初安装时通过 AJAX 请求从 SQL Server 数据库检索数据(组件在下面执行了安装功能)。我通过 .Net/C# 完成服务器端的工作,并通过 xhttp.responseText 和 string.prototype.split 将数据返回客户端到数组中。为了加快调试速度,我跳过了 ajax 请求,每次都不依赖数据库调用(因此检查 404 错误),相反,我将一个名为“n”的显式声明数组设置为类状态。我的下拉组件(有问题的组件)有一个名为“classes”的属性,该属性与类的当前状态(按上面的解释设置)相关,该代码也发布在下面。
类示例:
['justin','tom','bob']
渲染方法:
render: function(){
return(
<div>
<select onChange = {this.change}>
{
Object.keys(this.props.classes).map((value, key) =>{
return <option key = {key}>{value}</option>
}
)}
</select>
</div>
)
}
});
尝试了新代码:
export default React.createClass({
getInitialState: function(){
return{classes: this.props.classes }
},
render: function() {
var names = this.state.classes;
console.log(names);
return (
<select>
{names.map(function(name, index){
return <option key={ index }>{name}</option>;
})}
</select>
)
}
});
编辑 2 段代码:
componentDidMount: function(){
var xhttp;
var myStr;
var user = window.x;
console.log("the current user is "+ user);
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 || xhttp.status == 404) {
document.getElementById("test").innerHTML = xhttp.responseText;
myStr = xhttp.responseText;
//n = myStr.split("\n");
n = ['justin', 'earl', 'samuels', 'tom'];
console.log(n);
this.setState({ classes: n });
}
}.bind(this);
xhttp.open("GET", "/portals/0/js/hello.aspx?q="+user, true);
xhttp.send();
},
下拉组件:
<Dropdown classes = {this.state.classes} />
最佳答案
查看我的working example使用setTimeout来模拟异步调用。
重要的变化是您需要从 props
而不是 state
获取名称:
render: function() {
var names = this.props.classes;
console.log(names);
return (
<select>
{names.map(function(name, index){
return <option key={ index }>{name}</option>;
})}
</select>
)
}
以下代码:
export default React.createClass({
getInitialState: function(){
return{classes: this.props.classes }
},
render: function() {
var names = this.state.classes;
console.log(names);
return (
<select>
{names.map(function(name, index){
return <option key={ index }>{name}</option>;
})}
</select>
)
}
});
是anti-pattern 。因为 getInitialState
仅在首次创建组件时调用(classes
prop 是一个空数组),所以当组件接收到 classes prop(现在是数组)时,组件的状态不会更新异步调用成功后,使用来自服务器的数据。
关于javascript - React.JS - 值未显示在动态渲染列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37232772/