您好我正在尝试将map
我的Firebase中的数据转换为一排卡片。但是由于我在constructor
中定义了状态,因此在开始时会返回一张没有值的卡片。我该怎么做才能避免返回第一个空卡组件?提前谢谢。
(卡组件是我导入的缩略图的组件)
class List extends Component {
constructor(props){
super(props)
this.db = firebase.database().ref().child('app').child('cards');
this.state = {
cards: [
{
id: "",
cardDesc: "",
cardPrice: "",
cardHeading: "",
}
]
}
}
componentWillMount (){
const previousCards = this.state.cards
this.db.on('child_added', snap => {
previousCards.push ({
id: snap.key,
cardDesc: snap.val().cardDesc,
cardPrice: snap.val().cardPrice,
cardHeading: snap.val().cardHeading,
})
this.setState ({
cards: previousCards
})
})
}
render(){
return(
<div className='list'>
<Row>
{ this.state.cards.map((card) => {
return(<Card cardHeading={card.cardHeading} cardDesc={card.cardDesc}
cardPrice={card.cardPrice} key={card.id} />)
})
}
</Row>
</div>
)
}
}
export default List
答案 0 :(得分:1)
在数据返回之前无法延迟调用渲染方法,因此您可以检查cards.length是否为1并且在数据返回之前不显示任何内容或显示加载屏幕。
答案 1 :(得分:0)
您可以删除状态的初始设置,并将渲染方法更改为
var mysql = require('mysql');
var db = mysql.createConnection({
host :'localhost',
user :'root',
password :'root',
database :'nodejs'
});
db.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});