Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

reactjs - Is this the correct way to change a Firestore document with a button next to it?

This is a portion of the code to a react.js chat app. 'Lumens' are upvotes. Every message generates a new document which is sorted by its createdAt time. This all works.

I am attempting to print a button next to each 'message' document that adds 1 to its 'lumen' field. This code is no longer giving me errors- except the entire app fails to load. What am I doing wrong? I will post the rest of my code if desired.

function giveLumen(p){
  const db = firebase.firestore;
  const messages = db.collection('messages').doc(this)
  messages.update({lumens: 100})
}

function ChatMessage(props) {
  const { text, uid, photoURL, lumens } = props.message;

  const messageClass = uid === auth.currentUser.uid ? 'sent' : 'received';
  
  return (<>
    <div className={`message ${messageClass}`}>
      <img src={photoURL || 'https://api.adorable.io/avatars/23/[email protected]'} />

      
      <div className = "lumens">

        <button onClick= {giveLumen()} className="lumens">
        ??
        </button>

      </div>

      <p>{lumens}</p>
      <p>{text}</p>

    </div>
  </>)
}

Thanks for any help.


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

1 Answer

0 votes
by (71.8m points)

When you're passing giveLumen() with parenthesis you're calling the function

<button onClick= {giveLumen()} className="lumens">

In the first time, I think you should remove them. So that you'll pass the reference to you're function

<button onClick= {giveLumen} className="lumens">

// You can also write it as following (almost the same)

<button onClick= {() => giveLumen()} className="lumens">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...