javascript - 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}>️</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:解决方案- 我的脚本中有错字。消息拼写为“消息”。谢谢大家的帮助!
解决方案
这里的问题是当您使用解构时
const {foo} = bar
您应该是一个 bar 对象,它由一个foo
字段组成:
const bar = {
foo: ''
}
在您的情况下,您的props.messages
对象似乎不包含text
字段,这就是您收到错误的原因
推荐阅读
- search - 如何使用给定的特定参考来构建搜索优化模型,以识别来自具有 5TB 数据的 Data Lake 中的数据和文档
- git - 推送我的代码并创建 PR 表明其他人也提交了。为什么会这样?
- google-chrome - 如何重置我的 Drive for Desktop 存储空间?
- kubernetes - 大使主机 {hostname}:无效的 TLS 密钥 ssl-cert,标记为非活动
- spring - Spring,重新打包后没有“Access-Control-Allow-Origin”
- java - 如何保存当前时间或日期
- php - 当我尝试连接到谷歌电子表格时出现错误 - > 404“你需要许可”
- mysql - 在sql中创建可以接受多个参数的存储过程
- visual-studio-code - 搜索时在 VS 代码中出现 ENOENT 错误
- javascript - 如果在 div 中找到,则根据 if/else 条件替换 JS 中的值