我有一个从javascript类获取的javascript数组
export class BookStore {
constructor() {
this._books = [
{ id: 1,title: "How to Learn JavaScript - Vol 1", info: "Study hard"},
{ id: 2,title: "How to Learn ES6", info: "Complete all exercises :-)"},
{ id: 3,title: "How to Learn React",info: "Complete all your CA's"},
{ id: 4,title: "Learn React", info: "Don't drink beers, until Friday (after four)"
}
]
this._nextID= 5;
}
get books(){ return this._books;}
addBook(book){
book.id = this._nextID;
this._books.push(book);
this._nextID++;
}
}
然后,我调用books()
方法来获取数组中的对象。
然后我尝试将它们作为道具传递
const book = new BookStore()
console.log(book.books) //logs array
const books = book.books
console.log(books) // logs array
<Route path="/products" render={() => <Product products={books}/>} />
在产品组件内部,我console.log(this.props)
是一个空对象。
import React, { Component } from 'react'
export default class Product extends Component {
render() {
console.log(this.props) //logs `{}`
return (
<div>
<h1>Products</h1>
<p></p>
</div>
)
}
}
答案 0 :(得分:1)
编辑:我不知道JS对象(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)的get语法,谢谢@Callam。我提供的答案是不使用“ get”语法的解决方案,方法是显式定义成员函数并像标准函数一样使用它们。
我假设您可以执行此操作,因为我看到了导出语法 出口类BookStore { ... books =()=> this._books ... } 但是,如果获得语法,则可以在构造函数中显式绑定该函数
export class BookStore {
constructor() {
this.books = this.books.bind(this);
}
...
books() { return this._books; }
...
}
确保在实例化组件后调用getter方法:
const book = new BookStore(); const books = book.books(); }