在zustand中更新数组时丢失旧数据



export const useSocketDataStore = create((set) => ({
socketConnection: {},
setSocketConnection: (connection) => set({ socketConnection: connection }),
latestBidsFromSocket: [],
setLatestBidsFromSocket: (bids) => set({ latestBidsFromSocket: bids }),
}));

import { useSocketDataStore } from './store';
export const useUpdateSocketDataStore = () => {
const { latestBidsFromSocket, setLatestBidsFromSocket } =
useSocketDataStore();
const updateLatestBidsSocket = (data) => {
setLatestBidsFromSocket([data].concat(latestBidsFromSocket));
};
return { updateLatestBidsSocket };
};

我使用这个自定义钩子来更新数据库。但我松散的旧数据在latestBidsFromSocket当我尝试将新值连接到它时

我修复了这个问题。这是因为关闭。在updateLatestBidsSocket的每次函数调用中,传递给updateLatestBidsSocket函数的latestBidsFromSocket的值保持不变。

我更正了下面的代码。

import { useEffect, useState } from 'react';
import { useSocketDataStore } from './store';
export const useUpdateSocketDataStore = () => {
const { latestBidsFromSocket, setLatestBidsFromSocket } =
useSocketDataStore();
const [latestBidSocketData, setLatestBidSocketData] = useState({});
useEffect(() => {
if (Object.keys(latestBidSocketData).length) {
setLatestBidsFromSocket(
[latestBidSocketData].concat(latestBidsFromSocket)
);
}
}, [latestBidSocketData]);
return { setLatestBidSocketData };
};

如何:[…]数据,……latestBidsFromSocket)我从来没有遇到过这样连接数组的问题。

相关内容

  • 没有找到相关文章

最新更新