简体   繁体   English

ReactJS-将setState与Firebase一起使用

[英]ReactJS - Using setState with firebase listen

Well I already knew that we should do something like this to keep the state up to date with firebase changes. 好吧,我已经知道我们应该做这样的事情,以使状态随着Firebase的变化而更新。

import FirebaseRef from '...'
   .
.
.
class MyComponent extends React.Component {
 state = {
      maxVotes: 0  
    }

componentDidMount() {
   const { boardId } = this.props
   FirebaseRef.child(`boards/${boardId}/maxVotes`).on('value', snapshot => {
      this.setState({maxVotes: snapshot.val()})
   })
}

But my habit of coding is to delegate API call in other file and import it to component. 但是我编码的习惯是在其他文件中委派API调用并将其导入到组件中。 Can I do something like this? 我可以做这样的事情吗?

import { setMaxVotes } from ...
.
.
.
 componentDidMount() {
   const { boardId } = this.props
   setMaxVotes(boardId)
}

And how does the setMaxVotes method looklike ? 以及setMaxVotes方法的外观如何? Should I complicate thing like this, or it's not best pratice? 我应该把这样的事情复杂化,还是最好的做法?

It is common to delegate API calls to different modules but setting the react component state in different module is not a best practice. 通常将API调用委派给不同的模块,但是在不同的模块中设置react组件状态不是最佳实践。 So you can create different module for API calls but you should set the state in component itself. 因此,您可以为API调用创建不同的模块,但应在组件本身中设置状态。 The code may look something like this 该代码可能看起来像这样

componentDidMount() {
   const { boardId } = this.props
   setMaxVotes(boardId, 'value', snapshot => {
      this.setState({maxVotes: snapshot.val()})
   })
}

setMaxVotes(boardId, eventType, cb) {
   FirebaseRef.child(`boards/${boardId}/maxVotes`).on(eventType, cb);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM