React: Props在从父函数组件传递给子函数组件时未定义



我有一个聊天应用程序。

在App.js的函数组件中,我有一个初始化为空数组的messages状态。

import React, { useState, useEffect } from 'react';
import './App.css';
import Sidebar from './Sidebar';
import Chat from './Chat';
import Pusher from 'pusher-js';
import axios from './axios';
function App() {
const [messages, setMessages] = useState([]);
useEffect(() => {
axios.get('http://localhost:9000/messages/sync')
.then(response => {
console.log(response.data);
setMessages(response.data);
})
}, [])
// when function component loads, run the follow once
useEffect(() => {
const pusher = new Pusher('1693ef51485e86ca1e9f', {
cluster: 'us2',
});
const channel = pusher.subscribe('messages');
channel.bind('inserted', (newMessage) => {
alert(JSON.stringify(newMessage));
setMessages([...messages, newMessage]);
});
return () => {
channel.unbind_all();
channel.unsubscribe();
};
}, [messages])
return (
<div className="app">
<div className="app_body">
<Sidebar />
<Chat messsages={messages}/>
</div>
</div>
);
}
export default App;

一旦消息被存储在那里,消息状态就会作为道具传递给Chat.js中的函数组件。

import { Avatar, IconButton } from '@material-ui/core';
import SearchOutlinedIcon from '@material-ui/icons/SearchOutlined';
import AttachFileIcon from '@material-ui/icons/AttachFile';
import MoreVertIcon from "@material-ui/icons/MoreVert";
import InsertEmoticonIcon from '@material-ui/icons/InsertEmoticon';
import MicIcon from '@material-ui/icons/Mic';
import React from 'react';
import './Chat.css';
function Chat({ messages }) {
console.log(messages)
return (
<div className="chat">
<div className="chat_header">
<Avatar />
<div className="chat_headerInfo">
<h3>Room Name</h3>
<p>Last seen at...</p>
</div>
<div className="chat_headerRight">
<IconButton>
<SearchOutlinedIcon />
</IconButton>
<IconButton>
<AttachFileIcon />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>

<div className="chat_body">
{console.log(messages)}
{/**messages.map((message) => {
<p className={`chat_message ${message.received && "chat_receiver"}`}>
<span className="chat_name">{message.name}</span>
{message.message}
<span className="chat_timestamp">
{message.timestamp}    
</span>
</p>
}) */}

</div>
<div className="chat_footer">
<InsertEmoticonIcon />
<form>
<input placeholder="Type a message"
type="text"
/>
<button type="submit">
Send a message
</button>
</form>
<MicIcon />
</div>
</div>
)
}
export default Chat

然而,消息在聊天中是未定义的。

错误在哪里?我已经尝试过将道具传递给聊天:

function Chat (props) {
{console.log(props.message)}
}

似乎什么都不起作用。

检查

中的三个sss - messages的拼写
return (
<div className="app">
<div className="app_body">
<Sidebar />
<Chat messsages={messages}/>
</div>
</div>
);

很可能在第一个useEffect钩子中对localhost的请求没有返回响应值。再次检查控制台的输出。如前所述,它应该可以工作。

如果这看起来很好,那么我想说你需要清除你的构建缓存。

相关内容

最新更新