我有一个反应组件listBooks
正在传递道具bookShelf
。 bookShelf
道具是一组对象。每个对象都具有title
,author
,pageCount
等属性。
我想为每个对象添加一个Shelf属性。我试过了:
this.props.bookShelf.prototype.shelf = "";
这给了我一个错误TypeError: Cannot set property 'shelf' of undefined.
我也试过这个变种:
let bookShelf = this.props.bookShelf;
bookShelf.prototype.shelf = "none";
数组正由API调用中的对象填充。
componentDidMount(){
BooksAPI.getAll().then((bookShelf)=> {
this.setState({ bookShelf : bookShelf })
console.log(bookShelf)
})
我也尝试将上面的行放在这个功能中无济于事。
非常感谢指导!
答案 0 :(得分:1)
'bookShelf'prop是一个对象数组。每个对象都有 标题,作者,pageCount等属性。
我想为每个对象添加一个Shelf属性。
我不是你想在某个时候动态地做它,但你可以在map
状态下设置它时这样做:
componentDidMount(){
BooksAPI.getAll().then((bookShelf)=> {
bookShelf.forEach(b => {
b.shelf = "";
})
this.setState({ bookShelf })
})
答案 1 :(得分:0)
只需循环对象数组并指定属性:
this.props.bookShelf.map(book => book.shelf = "none");