[英]Is there a better way to pass props to a component in React?
這是我的主要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} />
)}/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.