将JavaScript数组作为prop传递给ReactJs

时间:2018-12-29 21:59:44

标签: javascript reactjs

我有一个从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>


   )
  }
}

1 个答案:

答案 0 :(得分:1)


编辑:我不知道JS对象(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)的get语法,谢谢@Callam。我提供的答案是不使用“ get”语法的解决方案,方法是显式定义成员函数并像标准函数一样使用它们。


  1. 代替使用get语法,只需使用标准函数并显式调用该函数即可获取所需的成员变量。还建议您将getter方法更改为匿名函数,这样就无需将实例显式绑定到函数:

我假设您可以执行此操作,因为我看到了导出语法     出口类BookStore {       ...       books =()=> this._books       ...     } 但是,如果获得语法,则可以在构造函数中显式绑定该函数

export class BookStore {
  constructor() {
    this.books = this.books.bind(this);
  }
  ...
  books() { return this._books; }
  ...
}
  1. 确保在实例化组件后调用getter方法:

    const book = new BookStore(); const books = book.books(); }

相关问题