我刚刚开始学习 React,我正在尝试找出如何找到我正在寻找的特定值。就像 Ruby 中有each.do 方法并且可以迭代数组一样,我正在尝试使用 React 来做到这一点。
class Gallery extends React.Component {
render () {
// debugger;
return (
<div>
<img> {this.props.gallery.thumbnail_url} </img>
</div>
)
}
}
我正在尝试访问thumbnail._url,但在使用调试器时,我无法访问所有对象和图像。我想到了 this.props.gallery.object.thumbnail_url 和其他想法,但我不太确定最好的方法!
最佳答案
使用Array.prototype.map()
将数据映射到 react 元素。并不是说循环中渲染的元素需要唯一标识符( keys ),以使重新渲染列表的性能更高。
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>
)
}
}
关于javascript - 如何使用 React (Rails) 迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40746168/