Javascript 在 React 中渲染 array.map()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38282997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rendering an array.map() in React
提问by Dmitry Birin
I am having a problem where I am trying to use array of data to render a <ul>
element. In the code below the console.log
's are working fine, but the list items aren't appearing.
我在尝试使用数据数组来呈现<ul>
元素时遇到问题。在下面的代码中console.log
's 工作正常,但列表项没有出现。
var Main = React.createClass({
getInitialState: function(){
return {
data: dataRecent
}
},
render: function(){
return (
<div>
<ul>
{
this.state.data.map(function(item, i){
console.log('test');
<li>Test</li>
})
}
</ul>
</div>
)
}
});
ReactDOM.render(<Main />, document.getElementById('app'));
What am I doing wrong? Please feel free to point out anything that isn't best practice.
我究竟做错了什么?请随时指出任何不是最佳实践的内容。
回答by Dmitry Birin
Gosha Arinichis right, you should return your <li>
element.
But, nevertheless, you should get nasty red warning in the browser console in this case
Gosha Arinich是对的,你应该返回你的<li>
元素。但是,无论如何,在这种情况下,您应该在浏览器控制台中收到令人讨厌的红色警告
Each child in an array or iterator should have a unique "key" prop.
数组或迭代器中的每个孩子都应该有一个唯一的“key” prop。
so, you need to add "key" to your list:
因此,您需要将“key”添加到您的列表中:
this.state.data.map(function(item, i){
console.log('test');
return <li key={i}>Test</li>
})
or drop the console.log()
and do a beautiful oneliner, using es6 arrow functions:
或者删除console.log()
并使用 es6箭头函数做一个漂亮的单行:
this.state.data.map((item,i) => <li key={i}>Test</li>)
IMPORTANT UPDATE:
重要更新:
The answer above is solving the current problem, but as Sergeymentioned in the comments: using the the key depending on the map index is BADif you want to do some filtering and sorting. In that case use the item.id
if id
already there, or just generate unique ids for it.
答案上面解决当前的问题,但作为谢尔盖在评论中提到:使用取决于地图索引关键是坏,如果你想要做一些过滤和排序。在这种情况下,使用item.id
ifid
已经存在,或者只是为它生成唯一的 id。
回答by Gosha Arinich
You are not returning. Change to
你不回来了。改成
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>;
})
回答by Najma Muhammed
let durationBody = duration.map((item, i) => {
return (
<option key={i} value={item}>
{item}
</option>
);
});
回答by Daniel A. White
You are implicitly returning undefined
. You need to return the element.
您正在隐式返回undefined
. 您需要返回元素。
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>
})
回答by Jee Mok
Add up to Dmitry's answer, if you don't want to handle unique key IDs manually, you can use React.Children.toArray
as proposed in the React documentation
加起来 Dmitry 的答案,如果您不想手动处理唯一键 ID,则可以React.Children.toArray
按照React 文档中的建议使用
React.Children.toArray
React.Children.toArray
Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
将子项不透明数据结构作为平面数组返回,其中键分配给每个子项。如果你想在你的渲染方法中操作子元素的集合,特别是如果你想在传递它之前重新排序或切片 this.props.children 时很有用。
Note:
React.Children.toArray()
changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element's key is scoped to the input array containing it.
笔记:
React.Children.toArray()
在展平子项列表时更改键以保留嵌套数组的语义。也就是说, toArray 为返回数组中的每个键添加前缀,以便每个元素的键范围限定为包含它的输入数组。
<div>
<ul>
{
React.Children.toArray(
this.state.data.map((item, i) => <li>Test</li>)
)
}
</ul>
</div>
回答by Radu Galan
I've come cross an issue with the implementation of this solution.
我在实施此解决方案时遇到了问题。
If you have a custom component you want to iterate through and you want to share the state it will not be available as the .map() scope does not recognize the general state() scope. I've come to this solution:
如果您有一个想要迭代的自定义组件并且想要共享状态,那么它将不可用,因为 .map() 范围无法识别一般 state() 范围。我来到了这个解决方案:
`
`
class RootComponent extends Component() {
constructor(props) {
....
this.customFunction.bind(this);
this.state = {thisWorks: false}
this.that = this;
}
componentDidMount() {
....
}
render() {
let array = this.thatstate.map(() => {
<CustomComponent that={this.that} customFunction={this.customFunction}/>
});
}
customFunction() {
this.that.setState({thisWorks: true})
}
}
class CustomComponent extend Component {
render() {
return <Button onClick={() => {this.props.customFunction()}}
}
}
In constructor bind without this.that
Every use of any function/method inside the root component should be used with this.that
在没有 this.that 的构造函数绑定中,根组件中任何函数/方法的每次使用都应该与this.that
回答by Thilina Imalka
import React, { Component } from 'react';
class Result extends Component {
render() {
if(this.props.resultsfood.status=='found'){
var foodlist = this.props.resultsfood.items.map(name=>{
return (
<div className="row" key={name.id} >
<div className="list-group">
<a href="#" className="list-group-item list-group-item-action disabled">
<span className="badge badge-info"><h6> {name.item}</h6></span>
<span className="badge badge-danger"><h6> Rs.{name.price}/=</h6></span>
</a>
<a href="#" className="list-group-item list-group-item-action disabled">
<div className="alert alert-dismissible alert-secondary">
<strong>{name.description}</strong>
</div>
</a>
<div className="form-group">
<label className="col-form-label col-form-label-sm" htmlFor="inputSmall">Quantitiy</label>
<input className="form-control form-control-sm" placeholder="unit/kg" type="text" ref="qty"/>
<div> <button type="button" className="btn btn-success"
onClick={()=>{this.props.savelist(name.item,name.price);
this.props.pricelist(name.price);
this.props.quntylist(this.refs.qty.value);
}
}>ADD Cart</button>
</div>
<br/>
</div>
</div>
</div>
)
})
}
return (
<ul>
{foodlist}
</ul>
)
}
}
export default Result;