是否有更好的方法将prop传递给React中的组件?

时间:2018-12-17 01:20:29

标签: javascript reactjs react-router react-props

这是我的主要app.js文件---我试图通过react-router-dom将此处定义为道具的状态值和函数传递给我的子组件:

import React, { Component } from 'react'

class BooksApp extends Component {

  state = {
    bookRepository: [{tuna: 'sandwhich'}],
    searchResults: [],
    featuredBook: {}
  }

  fixer = (someBooks, type) => { //code }

  async updateBookRepository(bookID, shelfID) { //code }

  async updateSearchResults(userQuery) { // code }

  async updateFeaturedBook(bookID, shelfID) {//code }


  render() {

    const myProps = {
      bookRepository:this.state.bookRepository,
      searchResults:this.state.searchResults,
      featuredBook:this.state.featuredBook, 
      updateBookRepository:this.updateBookRepository, 
      updateSearchResults:this.updateSearchResults, 
      updateFeaturedBook:this.updateFeaturedBook
    }

    return (
      <div>
        <Route exact path='/' render={(props) => (
          <Bookshelves {...props} {...myProps} />
        )}/>

        <Route path='/search' render={(props) => (
          <Searchpage {...props}  {...myProps}/>
        )}/>

        <Route path='/featuredBook/:bookID' render={(props) => (
          <Featuredbook {...props}  {...myProps}/>
        )}/>

      </div>
    )
  }
}

我正在像这样访问道具:

class Bookshelves extends Component {

  state = {
      shelves: ['currentlyReading', 'wantToRead', 'read']
    }

  render() {

    const { bookRepository } = this.props;

    return (
      <div>
      The props are: {console.log(this.props)}
      </div>
    )
  }
}

这有效,当我尝试访问它们时,它们全部显示在我的道具下,但是我在理解时遇到了麻烦,为什么我需要定义自己的对象,然后将其传递给我的子组件。

有什么方法可以将它们分配给props-ish对象本身,以便...

<Route exact path='/' render={(props) => (
  <Bookshelves {...props} />
}/>

...会把它们传下来吗?

1 个答案:

答案 0 :(得分:1)

您可以将所有内容分解成一行

<Route exact path='/' render={(props) => (
  <Bookshelves {...props, ...this.state} />
)}/>
相关问题