首页 > 解决方案 > TypeError:无法解构“props.message”的属性“text”,因为它未定义

问题描述

我的 ChatMessage 函数中出现 TypeError。

我尝试了几种不同的解决方案,但都与这个确切的场景无关。这是一个 Firebase 聊天应用程序,显然不是独一无二的,但我正在尝试将 TypeScript 集成到其中,仍在学习并希望找到一个我可以从中学到更多东西的解决方案。

App.tsx - 这是代码的核心

import './App.css';

import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';

import { useAuthState } from 'react-firebase-hooks/auth';
import { useCollectionData } from 'react-firebase-hooks/firestore';

firebase.initializeApp ({
    //Removed on stackoverflow for security reasons
})

const auth = firebase.auth();
const firestore = firebase.firestore();

function App() {
  const [user] = useAuthState(auth);

  return (
    <div className="App">
      <header>
        <h1>⚛️</h1>
        <SignOut />
      </header>

      <section>
        {user ? <ChatRoom /> : <SignIn />}
      </section>
    </div>
  );
}

function SignIn() {
  const signInWithGoogle = () => {
    const provider = new firebase.auth.GoogleAuthProvider();
    auth.signInWithPopup(provider);
  }

  return (
    <>
    <button onClick={signInWithGoogle}>Sign in with Google</button>
    <p>Do not violate the community guidelines or you will be banned for life!</p>
    </>
  )
}

function SignOut() {
  return auth.currentUser && (
    <button className="sign-out" onClick={() => auth.signOut()}></button>
  )
}

function ChatRoom() {
  const dummy = useRef<HTMLDivElement>(null);

  const messagesRef = firestore.collection('messages');
  const query = messagesRef.orderBy('createdAt').limit(25);

  const [messages] = useCollectionData(query, {idField: 'id'});

  const [formValue, setFormValue] = useState('');

  const sendMessage = async(e : any) => {
    e.preventDefault();

    const user = auth.currentUser;

    if (user) {
      const { uid, photoURL } = user;

      await messagesRef.add ({
        text: formValue,
        createdAt: firebase.firestore.FieldValue.serverTimestamp(),
        uid,
        photoURL
      });

      setFormValue('');
      dummy.current!.scrollIntoView({ behavior: 'smooth' });
      
    } else {
      //Handle Errors
    }
  };

  return (
    <>
      <main>
        {messages && messages.map((msg: any) => <ChatMessage key={msg.id} messsage={msg}/>)}

        <span ref={dummy}></span>
      </main>

      <form onSubmit={sendMessage}>
        <input value={formValue} onChange={(e) => setFormValue(e.target.value)} placeholder="Send Message..."/>
        <button type="submit" disabled={!formValue}>️&lt;/button>
      </form>
    </>
  )
}

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

  const messageClass = uid === auth.currentUser?.uid ? 'sent' : 'received';

  return (
    <>
    <div className={`message ${messageClass}`}>
      <img src={photoURL || 'https://api.hello-avatar.com/adorables/myseed'} />
      <p>{text}</p>
    </div>
    </>
  )
}

export default App;

ChatMessage 函数- 发生错误的函数(TypeScript 没有发现这个问题,它只在构建之后发生)

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

  const messageClass = uid === auth.currentUser?.uid ? 'sent' : 'received';

  return (
    <>
    <div className={`message ${messageClass}`}>
      <img src={photoURL || 'https://api.hello-avatar.com/adorables/myseed'} />
      <p>{text}</p>
    </div>
    </>
  )
}

Error - ChatMessage 函数中的特定错误

TypeError: Cannot destructure property 'text' of 'props.message' as it is undefined.

编辑1 - 我相信错误解释了“props.message”的属性“text”没有定义,尽管它的类型是“any”。我需要再次将其定义为特定类型吗?

编辑 2:解决方案- 我的脚本中有错字。消息拼写为“消息”。谢谢大家的帮助!

标签: javascriptreactjstypescriptfirebase

解决方案


这里的问题是当您使用解构时

const {foo} = bar

您应该是一个 bar 对象,它由一个foo字段组成:

   const bar = {
     foo: ''
  }

在您的情况下,您的props.messages对象似乎不包含text字段,这就是您收到错误的原因


推荐阅读