This is my main app.js file --- I'm trying to pass down the state values and functions defined here as props to my child components through 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>
)
}
}
I'm accessing the props like so:
class Bookshelves extends Component {
state = {
shelves: ['currentlyReading', 'wantToRead', 'read']
}
render() {
const { bookRepository } = this.props;
return (
<div>
The props are: {console.log(this.props)}
</div>
)
}
}
And this works, and they show all show up under my props when I attempt to access them, but I'm having trouble udnerstanding WHY I need to define my own object and then pass that down to my child components.
Is there some way that I can assign them to the props
-ish object itself so that...
<Route exact path='/' render={(props) => (
<Bookshelves {...props} />
}/>
...would pass them down?
You can destructure everything in one line
<Route exact path='/' render={(props) => (
<Bookshelves {...props, ...this.state} />
)}/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.