我試圖渲染ProfilePage
組件內的BookList
組件,但我遇到了一個我自己無法修復的問題,主要是因爲我完全不知道原因是什麼。
這裏是ProfilePage
組件:當試圖渲染另一個組件內的組件時,道具變得不確定
import React from 'react';
import { connect } from 'react-redux';
import { getUser, deleteBook } from '../actions/actions';
import { addFlashMessage } from '../actions/flashMessages';
import BookList from './BookList';
class ProfilePage extends React.Component {
componentWillMount =() => {
// Get user data by username
this.props.getUser(this.props.match.params.username)
.catch(err => {
this.props.addFlashMessage({
type: 'error',
text: err.response.data.error,
})
});
};
render() {
const { picture, name, email, books } = this.props.profileUser;
console.log(picture, name, email, books);
const whenOwner = (
<div className="extra">
<div className="ui right floated primary button">
Edit
<i className="right edit icon"></i>
</div>
</div>
);
return (
<div className="ui items">
<div className="item">
<div className="ui small image">
<img src={picture || 'https://semantic-ui.com/images/wireframe/image.png'} alt="Profile picture"/>
</div>
<div className="content">
<div className="header">
{name}
</div>
<div className="description">
<p>{email}</p>
</div>
{this.props.currentUser && whenOwner}
</div>
</div>
{/*<BookList books={books} deleteBook={this.props.deleteBook}/>*/}
</div>
)
}
}
function mapStateToProps(state) {
if(state.auth.isAuthenticated) {
return {
currentUser: state.auth,
profileUser: state.user
}
} else {
console.log(state);
return {
profileUser: state.user
}
}
}
React.propTypes = {
profileUser: React.PropTypes.object.isRequired,
currentUser: React.PropTypes.object,
};
export default connect(mapStateToProps, { getUser, addFlashMessage, deleteBook })(ProfilePage);
當BookList
被註釋掉頁面呈現就好了。 BookList
的相關道具也都在那裏。但只要我取消註釋BookList
我收到一個錯誤,books
(this.props.profileUser.books
)未定義。 這是確切的錯誤陣營拋出:
TypeError: Cannot read property 'map' of undefined
BookList
C:\Users\erody\WebstormProjects\book_trading_club\src\components\BookList.js:16
我懷疑有與BookList
成分本身有問題,因爲我使用的是別的地方,它工作正常那裏。但在這裏它是反正:
import React from 'react';
import BookCard from './BookCard';
const BookList = ({books, deleteBook}) => {
console.log(books);
const emptyMessage = (
<p>
There are no books.
</p>
);
const bookList = (
<div className="ui five cards">
{ books.map(book => <BookCard deleteBook={deleteBook} book={book} key={book._id}/>)}
</div>
);
return (
<div>
{books.length ? bookList : emptyMessage}
</div>
)
};
BookList.propTypes = {
books: React.PropTypes.array.isRequired,
deleteBook: React.PropTypes.func.isRequired
};
export default BookList;
當通過Redux devtools查看一切似乎很好。該操作被分派並且狀態被正確更新。
如果我添加了動作和相關的縮減器,我也可以添加這些動作,但我不想讓這篇文章太長。
我看來,像'this.props.profileUser.books'不是一個數組。你能顯示你的console.log輸出嗎? –