Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

reactjs - React + Firebase using hooks?

I found a great tutorial on using React with Firebase for a very simple use of just storing a text field's data in a database, but I'm stumped on how to convert it to using Hooks. There aren't many tutorials I could find out there on using Hooks + Firebase, so I'd appreciate any help!

import React, {useState} from 'react'
import fire from './fire'
import './App.css'

const App = () => {
  let [messageList, setMessageList] = useState([])

  const handleSubmit = (e) => {
    e.preventDefault()
  }

  return(
    <section>
    <form onSubmit={handleSubmit}>
      <input type="text"></input>
      <button>Test</button>
    </form>
    <span>Messages: {messageList}</span>
    </section>
  )
}

class ThisWorksButNotWithHooks extends React.Component {
  constructor(props) {
    super(props);
    this.state = { messages: [] }; // <- set up react state
  }
  componentWillMount(){
    /* Create reference to messages in Firebase Database */
    let messagesRef = fire.database().ref('messages').orderByKey().limitToLast(100);
    messagesRef.on('child_added', snapshot => {
      /* Update React state when message is added at Firebase Database */
      let message = { text: snapshot.val(), id: snapshot.key };
      this.setState({ messages: [message].concat(this.state.messages) });
    })
  }
  addMessage(e){
    e.preventDefault(); // <- prevent form submit from reloading the page
    /* Send the message to Firebase */
    fire.database().ref('messages').push( this.inputEl.value );
    this.inputEl.value = ''; // <- clear the input
  }
  render() {
    return (
      <form onSubmit={this.addMessage.bind(this)}>
        <input type="text" ref={ el => this.inputEl = el }/>
        <input type="submit"/>
        <ul>
          { /* Render the list of messages */
            this.state.messages.map( message => <li key={message.id}>{message.text}</li> )
          }
        </ul>
      </form>
    );
  }
}

export default App;

I know it's communicating with Firebase properly because ThisWorksButNotWithHooks works, thanks to https://www.codementor.io/yurio/all-you-need-is-react-firebase-4v7g9p4kf . I learn best by seeing a barebones simple example and working up from there by trial and error, so if I knew how to do this with Hooks I could work up to more complex usage.

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...