You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件如何获取新数据后保留旧数据并追加展示?

解决方案

要实现保留旧消息并追加新消息的效果,核心是修改状态更新逻辑,不再直接覆盖原有状态,而是基于历史状态累积新内容。以下是两种可行的修改方案:

方案一:使用数组存储所有消息(推荐,更灵活)

将状态从单个对象改为数组,每次请求到新消息时,将其追加到数组中(可按需去重):

export default function LogMessage () {
    // 改为数组存储所有日志消息
    const [logMessages, setLogMessages] = useState([]);
    
    const fetchData = async () => {
        try {
            const response = await fetch('http://localhost:8989/get-log');
            const data = await response.json();
            
            // 仅当有新消息时更新状态
            if (Object.keys(data).length > 0) {
                const newMessages = Object.values(data);
                setLogMessages(prev => {
                    // 过滤掉已存在的消息(避免重复)
                    const uniqueNew = newMessages.filter(msg => !prev.includes(msg));
                    return [...prev, ...uniqueNew];
                });
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };
    
    useEffect(() => {
        const interval = setInterval(() => {
            fetchData();
        }, 1000);
        return () => clearInterval(interval);
    }, []);

    return (
        <div className="log">
            <p>Logger</p>
            <div className="log_wrapper">
                {/* 遍历数组渲染所有消息 */}
                {logMessages.map((message, index) => (
                    <span key={index}>{message}</span>
                ))}
            </div>
        </div>
    )
}

关键修改点:

  • 状态从{}改为数组[],用于存储所有历史消息
  • 更新状态时,先判断返回的data是否非空,再提取新消息并过滤重复项,最后与历史消息合并
  • 渲染时遍历数组,用索引作为key(如果消息有唯一标识,建议用标识代替索引)

方案二:使用对象累积消息(适用于服务器返回唯一key的场景)

如果服务器每次返回的新消息key(如message1、message2)都是唯一且不重复的,可直接合并对象:

export default function LogMessage () {
    const [logMessage, setLogMessage] = useState({});
    
    const fetchData = async () => {
        try {
            const response = await fetch('http://localhost:8989/get-log');
            const data = await response.json();
            
            if (Object.keys(data).length > 0) {
                // 合并新旧消息对象,新key会自动添加,旧key不会被覆盖
                setLogMessage(prev => ({...prev, ...data}));
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };
    
    useEffect(() => {
        const interval = setInterval(() => {
            fetchData();
        }, 1000);
        return () => clearInterval(interval);
    }, []);

    return (
        <div className="log">
            <p>Logger</p>
            <div className="log_wrapper">
                {Object.entries(logMessage).map(([key, message]) => (
                    <span key={key}>{message}</span>
                ))}
            </div>
        </div>
    )
}

关键修改点:

  • 更新状态时使用扩展运算符{...prev, ...data}合并新旧对象,保留原有消息的同时添加新消息
  • 渲染时用消息的key作为React元素的key,确保渲染稳定

内容的提问来源于stack exchange,提问作者Sashko1121

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 01:10:55