我的代码似乎重复了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}  {valu.category}  {valu.replies}  {valu.views}  {valu.activity}</div>))) : null}
</div>);
}
}
export default App;
答案 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}  {category}  {replies}  {views}  {activity}
</div>
))
: null // otherwise, show null if this.state.value is empty
)
}
export default App;