我正在尝试使用React从firebase渲染数组。我有一个Container视图,它从firebase获取数据,并将数据传递给子组件。这是代码:
Container.jsx
import React from 'react'
import Firebase from 'firebase'
import loadsTable from './loadstable'
class Container extends React.Component{
constructor(props){
super(props)
this.loads = [];
this.state = {loads:[]}
}
render(){
console.log("render" , this.state.loads)
return( <div>
<loadsTable loads={this.state.loads}/>
</div>
)
}
componentWillMount(){
this.firebaseRef = new Firebase("https://***.firebaseio.com/loads");
this.firebaseRef.on("child_added", function(dataSnapshot) {
console.log(dataSnapshot.val())
this.loads.push(dataSnapshot.val());
this.setState({
loads: this.loads
});
}.bind(this));
}
}
React.render(<Container/> , document.getElementById('app'))
这成功获取数据(加载),console.logs也一样。
以下是子组件的代码:
LoadsTable.jsx
import React from 'react'
class loadsTable extends React.Component{
constructor(props){
super(props)
console.log("init loadsTable");
this.state = {loads:this.props.loads}
}
render(){
console.log("this.state.loads " , this.props.loads);
console.log("this.state.loads " , this.state.loads);
var loads = this.props.loads.map(function(load, index){
console.log("load " , load)
return <tr><td>{load.load_number}</td></tr>
});
return(
<div className="col-md-7">
<table className="table table-hover table-bordered table-striped loads">
<tbody>
{loads}
</tbody>
</table>
</div>
)
}
}
export default loadsTable
这里的问题是没有任何东西被渲染,实际上,构造函数中的console.log永远不会被调用。如果我在Container构造函数中调用LoadsTable,我得到:
Chrome开发者控制台输出
function loadsTable(props) {
_classCallCheck(this, loadsTable);
_get(Object.getPrototypeOf(loadsTable.prototype), "constructor", this).call(this, props);
console.log("init loadsTable");
this.state = { loads: this.props.loads };
}
所以,我的问题是:有没有人知道我在这里做错了什么以及为什么没有实例化LoadsTable?
我正在使用Gulp来构建和传播ES6。
对此的任何帮助都将非常感激。提前谢谢。
答案 0 :(得分:2)
组件名称必须大写。所以它应该是
import LoadsTable from ...;
和
<LoadsTable ... />
代替。
请参阅https://facebook.github.io/react/docs/jsx-in-depth.html#html-tags-vs.-react-components