我正在制作一个聊天应用程序,我想获取聊天内容,但这个问题来了。
response.data
一切正常,但状态未更新,并且在设置状态后为 console.log("chats updated:", chats)
打印 null。
import axios from 'axios';
import React, { useEffect, useState } from 'react';
function Chats() {
const [chats, setChats] = useState(null);
useEffect(() => {
const chload = async () => {
try {
const response = await axios.post('http://localhost:3001/getchats', {}, { withCredentials: true });
if (response.data) {
console.log(response.data);
setChats(response.data);
console.log("chats updated:", chats);
}
} catch (error) {
console.error('Error fetching chats:', error);
}
};
chload();
}, []);
return (
<>
{chats !== null ? (
<>
<p>{chats.name}</p>
</>
) : (
<p>Loading chats...</p>
)}
</>
);
}
export default Chats;