这是我的主要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} />
}/>
……会把它们传下来吗?
最佳答案 你可以在一条线上解构所有东西
<Route exact path='/' render={(props) => (
<Bookshelves {...props, ...this.state} />
)}/>