我的代码使其重复5次的问题是什么?

时间:2018-11-24 14:18:13

标签: javascript reactjs

我的代码似乎重复了5次: 找不到原因:

    import React, { Component } from "react";
    class App extends Component {
        state = { value: [{ title: "my title", category: "action", replies: "62", views: "26k", activity: "18h" }] };
        render() {
            return (
                <div>{this.state.value ? this.state.value.map(valu => 
                    Object.keys(valu).map((tr, index) => (
                <div key={index}>{valu.title}&emsp;&emsp;{valu.category}&emsp;&emsp;{valu.replies}&emsp;&emsp;{valu.views}&emsp;&emsp;{valu.activity}</div>))) : null}
                </div>);
        }
    } 
    export default App;

1 个答案:

答案 0 :(得分:0)

删除obj(keys)(它创建了不必要的附加循环),而只是在map上仅this.state.value。然后为key使用唯一属性(理想情况下,这应该是由数据库分配的id)。

import React, { Component } from "react";

class App extends Component {
  state = { value: [{ id: "b5dc-58f6-u3ga-fbb4", title: "my title", category: "action", replies: "62", views: "26k", activity: "18h" }] };

  render = () => (
    this.state.value && this.state.value.length > 0 // if value exists and is greater than 0...
      ? this.state.value.map(({ id, title, category, replies, views, activity }) => ( // map over value array and deconstruct the properties (eliminates the need to do value.title, value.category...etc)
          <div key={id}>
             {title}&emsp;&emsp;{category}&emsp;&emsp;{replies}&emsp;&emsp;{views}&emsp;&emsp;{activity}
          </div>
         ))
        : null // otherwise, show null if this.state.value is empty
   )
} 

export default App;