【发布时间】:2017-04-19 07:05:10
【问题描述】:
下面的反应代码在第一次运行时从 Firebase 获取数据快照。 this.state.term 指的是我的 Firebase 数据库中节点的索引。我的handleChoice 函数执行this.setState,但它似乎没有重新渲染这个组件来获取新的数据快照。
this.state.term 的值在componentDidMount 下没有变化。但是,当我在渲染中控制台记录它时,它确实如此。
import React, { Component } from 'react';
import NavBar from './navbar.js';
import TermInfo from './termInfo.js';
import * as firebase from 'firebase';
import './App.css';
class App extends Component {
constructor(){
super();
this.state = {
term: 66, //sample term to load first
examples: [1,2,3],
dataNode: {},
}
}
componentDidMount(){
let rootRef = firebase.database().ref('vocab/').child(this.state.term);
rootRef.on('value', snap => {
this.setState({
dataNode: snap.val(),
examples: Object.assign([], snap.val().examples)
});
});
}
_handleChoice(theChosenOne){
this.setState({
term: theChosenOne
});
}
render() {
console.log(this.state.term); //this gives me the right index
return (
<div className="App">
<div className="App-header">
<NavBar choose={this._handleChoice.bind(this)}/>
</div>
<div className='container'>
<div className="jumbotron"><TermInfo node={this.state.dataNode} examples={this.state.examples}/>
<p className="App-intro">
Enter a vocabulary term to search for and add examples!
</p></div>
</div></div>
);
}
}
export default App;
为什么它不重新渲染并重新抓取数据?
【问题讨论】:
标签: reactjs firebase firebase-realtime-database