我之前已经这样做过并且提供了 key ,但由于某种原因我仍然收到错误。我的 react 有点新,所以这可能是某个地方的一个愚蠢的错误。
编辑:错误是数组中的每个子项都应该有一个唯一的键
这是代码:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
class BooksList extends Component {
renderList() {
return _.map(this.props.books, book => {
return (
<div key={book.id}>
<h2>{book.title}</h2>
<h3>{book.description}</h3>
<h4>{book.price}</h4>
</div>
);
});
}
render() {
return (
<div>
{this.renderList()}
</div>
);
}
}
function mapStateToProps(state) {
return {
books: state.books
}
}
export default connect(mapStateToProps)(BooksList);
编辑:
我尝试在构造函数中绑定(bind) this.renderList
,但仍然存在相同的问题:
constructor(props) {
super(props);
this.renderList = this.renderList.bind(this);
}
最佳答案
您的问题是您在 map 最初发生之前没有加载书籍..因此您最初的数据无效。
最初this.props.books
是这个
解决此问题的方法是仅在拥有有效对象时进行渲染。使用 lodash isEmpty 检查对象...使用 forEach 这样就不会在数组中返回空(数组中保存的项目较少)。然后在最后返回该数组:)
renderList() {
const elems = [];
_.forEach(this.props.books, book => {
if (_.isEmpty(book)) return;
elems.push(
<div key={book.id}>
<h2>{book.title}</h2>
<h3>{book.description}</h3>
<h4>{book.price}</h4>
</div>
);
});
return elems;
}
关于javascript - 我为每个 react 的 child 提供了一个 key ,但我仍然收到错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44397728/