【发布时间】:2021-10-10 19:07:27
【问题描述】:
简而言之:
我有一个包含对象列表的状态变量
当我单击一个按钮时,会调用一个方法,该方法会使用 setState 方法将一个对象添加到列表中。
状态不更新。 此外,列表应该使用 .map 函数呈现
短代码(仅重要部分)
const [chat, setChat] = useState([]);
...
function addMessage(msg: Message) {
let newChat = chat;
// @ts-ignore
newChat.push(msg);
setChat(newChat);
}
...
{chat.map((e: Message) => (
<Message
key={e.msg}
content={e.msg}
author={e.author}
self={e.author === self}
/>
))}
...
<Messageinput
sendMessage={(m) => {
addMessage({ msg: m, author: "You" });
}}
完整代码(整个组件)
interface Message {
msg: string;
author: string;
}
export default function Chat({
messages,
self,
}: {
messages: Array<Message>;
self: string;
}) {
const [chat, setChat] = useState([]);
useEffect(() => {
// @ts-ignore
setChat(messages);
}, []);
function addMessage(msg: Message) {
let newChat = chat;
// @ts-ignore
newChat.push(msg);
setChat(newChat);
}
useEffect(() => {
console.log("chat state changed: ", chat);
}, [chat]);
return (
<div
className="flex flex-col bg-white bg-opacity-10 rounded-3xl p-4 max-w-sm"
style={{ maxHeight: "720px", height: "100%" }}
>
<div className="overflow-y-auto h-full">
{chat.map((e: Message) => (
<Message
key={e.msg}
content={e.msg}
author={e.author}
self={e.author === self}
/>
))}
</div>
<Messageinput
sendMessage={(m) => {
addMessage({ msg: m, author: "You" });
}}
/>
</div>
);
}
【问题讨论】:
标签: reactjs typescript next.js state