我正在尝试从Firebase实时数据库中读取数据,并将该对象传递给React中的组件作为其状态,以便组件可以在对数据库进行任何更改时自动呈现。我检索的数据存储在变量local_data中,并将传递给Full组件。
然而,当以这种方式实现时,页面会不断地保持刷新。相反,如果对数据库进行任何更改,我希望它只显示实时更新。
以下是相关的代码片段(在Full.js中将this.state传递给Charts):
index.js
var local_data = {}
window.location.reload();
ReactDOM.render((
<div>
<HashRouter>
<Switch>
<Route exact path="/login" name="Login Page" component={Login}/>
<Route exact path="/register" name="Register Page" component={Register}/>
<Route exact path="/404" name="Page 404" component={Page404}/>
<Route exact path="/500" name="Page 500" component={Page500}/>
<Route path="/original" name="Home" component={Full} sample={local_data}/>
<Route path="/" name="Home" render={props => <Full local_data= {local_data} />} />
</Switch>
</HashRouter>
</div>
), document.getElementById('root'));
Full.js
class Full extends Component {
constructor(props) {
super(props);
//Change this to be an object to iterate.
console.log("In Full.js ->",props.local_data.greeting);
this.state = {};
}
componentWillMount(){
/* Create reference to messages in Firebase Database */
let db = firebase.database().ref('/');
db.off();
db.on('value', snapshot => {
/* Update React state when message is added at Firebase Database */
let locData = snapshot.val();
//this.setState(locData);
this.state = locData;
})
}
render() {
return (
<div className="app">
<Header />
<div className="app-body">
<Sidebar {...this.props}/>
<main className="main">
<Breadcrumb />
<Container fluid>
<Switch>
<Route path="/dashboard" name="Dashboard" component={Dashboard}/>
<Route path="/components/buttons" name="Buttons" component={Buttons}/>
<Route path="/components/cards" name="Cards" component={Cards}/>
<Route path="/components/forms" name="Forms" component={Forms}/>
<Route path="/components/modals" name="Modals" component={Modals}/>
<Route path="/components/social-buttons" name="Social Buttons" component={SocialButtons}/>
<Route path="/components/switches" name="Swithces" component={Switches}/>
<Route path="/components/tables" name="Tables" component={Tables}/>
<Route path="/components/tabs" name="Tabs" component={Tabs}/>
<Route path="/icons/font-awesome" name="Font Awesome" component={FontAwesome}/>
<Route path="/icons/simple-line-icons" name="Simple Line Icons" component={SimpleLineIcons}/>
<Route path="/widgets" name="Widgets" component={Widgets}/>
<Route path="/charts_original" name="Charts" component={Charts} />
<Route path="/charts" name="Charts" render={props => <Charts local_data={this.state} {...props} />} />
<Redirect from="/" to="/dashboard"/>
</Switch>
</Container>
</main>
<Aside />
</div>
<Footer />
</div>
);
}
}
export default Full;
答案 0 :(得分:0)
在Full.js的componentDidMount中使用db.on('value', snap => this.setState(snap.val()))
。 React不喜欢你直接改变状态https://reactjs.org/docs/react-component.html#state