2015-10-20 125 views
1

当我控制台登录状态它返回未定义,但在我的反应开发工具,我可以看到结果数组。 这是组件:反应组件未更新状态

var Categorias = React.createClass({ 
    getInitialState: function() { 
    return { 
     items: [] 
    }; 
    }, 

componentWillMount: function(){ 
    var firebaseRef = new Firebase("https://rapifood.firebaseio.com/categorias"); 
    firebaseRef.on("child_added", function(dataSnapshot) { 
    var items= []; 
    items.push(dataSnapshot.val()); 
    this.setState({ 
     items: items 
    }); 
    }.bind(this)); 
}, 

componentDidMount: function() { 
    console.log(this.state.items); 
}, 

我在做什么错?

+0

你可能想尝试把'console.log'在渲染功能。在'componentDidMount'被触发时,不确定数据是否存在 – pmilla1606

回答

0

这是因为您正在设置ajax回调的状态,该回调在初始渲染(componentDidMount)之后完成。

+0

更好方法的例子? – Kato

0

你可能想有另一种状态变量来跟踪的加载状态:

var Categories = React.createClass({ 
    getInitialState: function() { 
    return { 
     loaded: false, 
     items: [] 
    }; 
    }, 

    componentWillMount: function(){ 
    var firebaseRef = new Firebase("https://rapifood.firebaseio.com/categorias"); 
    firebaseRef.on("child_added", function(dataSnapshot) { 
     this.setState({ 
     loaded: true, 
     items: this.state.items.concat(dataSnapshot.val()) 
     }); 
    }.bind(this)); 
    }, 

    componentWillUnmount: function() { 
    // Don't forget to remove the Firebase subscription here. 
    } 

    render: function() { 
    if (!this.state.loaded) { 
     return <div>Loading...</div>; 
    } 
    // Now you can render the list of items here. 
    }, 
});