我正在开发一个 react 应用程序,我遇到了这个奇怪的错误,我试图在前端显示 props 值,但它什么也没显示,但是,如果我尝试 console.log
这些 Prop 的值(value),我得到了正确的值(value)。这是我的代码。
import React, { Component } from 'react';
import { connect } from 'react-redux';
class BookList extends Component{
renderBooks = () => {
if( this.props.books.length === 0 ){
console.log("No books");
return <p>Getting books...</p>
}else{
console.log( this.props.books[0].id );
return <h2> { this.props.books[0].id }</h2>//this.props.books.map(( book ) => {
// return (
// <div key={ book.id }>
// <h2>{ book.title }</h2>
// <h2>{ book.description }</h2>
// <h3>{ book.price }</h3>
// </div>
// )
//});
}
}
render(){
return(
<div>
{ this.renderBooks() }
</div>
)
}
}
function mapStateToProps( state ){
return {
books: state.books.books
}
}
export default connect( mapStateToProps )(BookList);
map 功能也无法使用。在控制台中,我得到了正确的 props 值,当我尝试检查此 <div>
的 HTML 元素时,我明白了。
<div>
<h2></h2>
</div>
标签中没有任何内容。为什么会发生这种情况以及如何解决它?
最佳答案
这样调试怎么样?
let dummyBooks = [
{ id: 1, title: 't1', description: 'd1', price: 1 },
{ id: 2, title: 't2', description: 'd2', price: 2 },
];
return dummyBooks.map(( book ) => {
return (
<div key={ book.id }>
<h2>{ book.title }</h2>
<h2>{ book.description }</h2>
<h3>{ book.price }</h3>
</div>
)
});
如果没问题 - 那么肯定是有错误
this.props.books
也许它是一个对象,而不是一个数组?
关于javascript - Prop 在控制台中工作,但不在前端渲染 - React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50276119/