Javascript 如何使用React(Rails)遍历数组
我刚刚开始学习React,我正试图找出如何找到我正在寻找的特定价值。就像在Ruby中有each.do方法,可以遍历数组一样,我尝试使用React来实现这一点Javascript 如何使用React(Rails)遍历数组,javascript,arrays,debugging,reactjs,Javascript,Arrays,Debugging,Reactjs,我刚刚开始学习React,我正试图找出如何找到我正在寻找的特定价值。就像在Ruby中有each.do方法,可以遍历数组一样,我尝试使用React来实现这一点 class Gallery extends React.Component { render () { // debugger; return ( <div> <img> {this.props.gallery.thumbnail_url} </img>
class Gallery extends React.Component {
render () {
// debugger;
return (
<div>
<img> {this.props.gallery.thumbnail_url} </img>
</div>
)
}
}
类库扩展了React.Component{
渲染(){
//调试器;
返回(
{this.props.gallery.thumbnail\u url}
)
}
}
我正在尝试访问缩略图。当使用调试器时,我无法访问所有对象和图像。我想到了这个.props.gallery.object.thumbnail\u url和其他想法,但我不确定最好的方法是什么 使用
Array.prototype.map()
将数据映射到react元素。并不是说在循环中呈现的元素需要唯一标识符(),以使重新呈现列表的性能更好
class Gallery extends React.Component {
render () {
const { gallery = [] } = this.props; // destructure the props with a default (not strictly necessary, but more convenient)
return (
<div>
{
gallery.map(({ id, thumbnail_url }) => (
<img key={ id } src={ thumbnail_url } />
))
}
</div>
)
}
}
类库扩展了React.Component{
渲染(){
const{gallery=[]}=this.props;//使用默认值(不是严格必需的,但更方便)对props进行解构
返回(
{
gallery.map({id,缩略图_url})=>(
))
}
)
}
}
您可以执行以下操作:
class Gallery extends React.Component {
render () {
// initialize 'images' to empty array if this.props.gallery is undefined
// other wise 'images.map' will throw error
const images = this.props.gallery || [];
return (
<div>
{images.map((image, index) => <img src={image.thumbnail_url} key={index} />)}
</div>
)
}
}
类库扩展了React.Component{
渲染(){
//如果this.props.gallery未定义,则将“images”初始化为空数组
//其他wise“images.map”将抛出错误
const images=this.props.gallery | |[];
返回(
{images.map((图像,索引)=>)}
)
}
}
您可能已经注意到了propkey={index}
。如果忽略此项,您将看到一条警告:
数组或迭代器中的每个子级都应该有一个唯一的“键”属性
实际上,它不是作为prop传递给组件,而是由React用于帮助协调集合。这种方法可以处理最小的DOM更改