我有一个 react 组件listBooks
,它正在传递一个 Prop bookShelf
。 bookShelf
属性是一个对象数组。每个对象都有诸如 title
、author
、pageCount
等属性。
我想为每个对象添加一个 Shelf 属性。我试过:
this.props.bookShelf.prototype.shelf = "";
这给了我一个错误TypeError:无法设置未定义的属性“shelf”。
我也尝试过这个变体:
let bookShelf = this.props.bookShelf;
bookShelf.prototype.shelf = "none";
该数组正在由 API 调用中的对象填充。
componentDidMount(){
BooksAPI.getAll().then((bookShelf)=> {
this.setState({ bookShelf : bookShelf })
console.log(bookShelf)
})
我也尝试将上面的行放入此函数中,但无济于事。
指导将不胜感激!
最佳答案
The 'bookShelf' prop is an array of objects. Each object has properties such as title, author, pageCount.
I would like to add a Shelf property to each of the objects.
我不知道你是否想在某个时刻动态地执行此操作,但当你使用 map
将它们设置为状态时可以执行此操作:
componentDidMount(){
BooksAPI.getAll().then((bookShelf)=> {
bookShelf.forEach(b => {
b.shelf = "";
})
this.setState({ bookShelf })
})
关于javascript - 如何在 React 中向 prop 添加新属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50294982/