React + Firebase 使用钩子? [英] React + Firebase using hooks?

查看:17
本文介绍了React + Firebase 使用钩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一个关于将 React 与 Firebase 一起使用的很棒的教程,它非常简单地将文本字段的数据存储在数据库中,但我对如何将其转换为使用 Hooks 感到困惑.我找不到很多关于使用 Hooks + Firebase 的教程,所以我很感激任何帮助!

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;

感谢 https://www.codementor.io/yurio/all-you-need-is-react-firebase-4v7g9p4kf.我通过查看准系统的简单示例并通过反复试验来获得最好的学习效果,所以如果我知道如何使用 Hooks 做到这一点,我就可以处理更复杂的用法.

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.

谢谢!

推荐答案

这样的事情应该可行.我并没有真正关注您的 Firebase 逻辑或返回的 html,只是展示了如何使用 useEffect 和 useState 钩子:

Something like this should work. I haven't really focused on your Firebase logic or returned html, but just showed how you could use the useEffect and useState hooks:

const App = () => {
  const [messageList, setMessageList] = useState([])
  const [inputEl, setInputEl] = React.useState(null)
  
  React.useEffect(() => {
    /* Create reference to messages in Firebase Database */
    let messagesRef = fire.database().ref('messages').orderByKey().limitToLast(100);

    // As you are using a listener, declare it so it can be returned
    const listener = messagesRef.on('child_added', snapshot => {

      // Below logic just adds to the current 'messages' state  
      const message = { text: snapshot.val(), id: snapshot.key };
      const updatedMessagesArray = [...messageList].push(message)
      setMessageList(updatedMessagesArray)
    })

    return () => listener() // <== the listener returns the unsubscribe function, which the hook will automatically run when the component unmounts.

  }, []) // <== run once onMount

  async function addMessage(e){
    e.preventDefault(); // <- prevent form submit from reloading the page
    /* Send the message to Firebase */
    await fire.database().ref('messages').push( inputEl.value );
    setInputEl(null)
  }
  
  const handleSubmit = (e) => {
    e.preventDefault()
  }

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

将一个空数组作为第二个参数传递给 useEffect 钩子将告诉它在组件挂载时只运行一次,并返回侦听器将让钩子在组件卸载时取消订阅侦听器.

Passing an empty array as the second arg to the useEffect hook will tell it only to run once when the component mounts, and returning the listener will let the hook unsubscribe the listener when the component unmounts.

这篇关于React + Firebase 使用钩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆