[英]Is there a better way to pass props to a component in React?
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: 这是我的主要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>
)
}
}
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... 有什么办法可以将它们分配给
props
-ish对象本身,以便...
<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} />
)}/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.