【问题标题】:Render list of Element from an Object in React从 React 中的对象渲染元素列表
【发布时间】:2020-05-30 16:06:46
【问题描述】:

我需要从一个对象动态呈现键值对。例如:

export default class App extends Component {
  state = {
    num: {
      cheese: 1,
      meat: 2,
      salad: 3,
    }
  }

  render() {
    const numLIst = Object.keys(this.state.num).map(key => {
      return [...Array(this.state.num[key])].map(() => {
        return <SmallComp content={key}/>
      } )
    })

所以我想渲染奶酪 1 次,肉类 2 次,沙拉 3 次。上面的代码来自课程的讲师,我不知道它在做什么

return [...Array(this.state.num[key])].map(() => {
        return <SmallComp content={key}/>
      } )

代码有效,但有更优雅的方法吗?

【问题讨论】:

  • 我感觉到你兄弟!我正在经历同样的课程;)但我成功地打破了逻辑并理解了他在做什么。不幸的是,我不记得他教这个的特定主题和视频标题。如果你能提到我将能够提供帮助。谢谢。
  • 这是第 129 课。

标签: javascript reactjs list


【解决方案1】:

你可以单独遍历 Object.keys...

没有更优雅的方式,只有其他方式......

  render() {
      const numList = Object.keys(this.state.num).map((name, index) => {
             return (new Array(index + )).map((_, subindex) => <SmallComp content={`${key}_${subindex}`}/>)
      });

      ....
    })

Object.keys(this.state.num) // 获取数组 ['cheese', 'meat', 'salad'];

(new Array(index + )) // 创建一个 (index + 1) 长度的数组

所以你循环遍历一个包含 n 个元素的数组来渲染...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-16
    • 2019-03-01
    • 2018-10-12
    • 2017-08-18
    • 2017-08-11
    • 2021-04-17
    • 2018-08-15
    • 2018-11-29
    相关资源
    最近更新 更多