问题描述
我正在使用 react-grid-layout 并创建一些网格可以拖放以及可调整大小.
I am working with react-grid-layout and creating some grids which are drag-drop as well as resizable.
所以我能够做到这一点,并且工作正常.
So i am able to achieve that and it is working fine.
我的UI就像我有两个选项卡,每个选项卡都有一些网格,因此当我从一个选项卡移到另外两个选项卡时,我正在显示该选项卡的网格.
My UI is like I have two tabs and each tab have some grids, so when I move from one tab two other I am showing that tab's grid.
我要做什么
在更改布局时,我想将该布局存储到本地存储中,以便当我再次刷新或打开该选项卡时,网格的形成应该是我所更改的.
On change of layout I want to store that layout to local storage so that when I refresh or open that tab again the formation of grid should be the one which I changed.
因此,按照提及的我正在图书馆中使用此
- 所以我正在做的是,每当发生
onLayoutChange
时,我都会相对于active_tab
存储布局,当我从一个选项卡更改为另一个选项卡时,我正在检查本地"存储并匹配哪个选项卡处于活动状态并获取该特定布局. - 但这并没有发生,只是采取了基本布局.
- So what I am doing is when ever
onLayoutChange
happens I am storing the layout with respect to myactive_tab
and when I change from one to other tab I am checking Local storage and matching which tab is active and getting that particular layout. - But this is not happening it is just taking the basic layout.
我做什么
function getFromLS(key) {
let ls = {};
if (global.localStorage) {
try {
ls =
JSON.parse(
global.localStorage.getItem(localStorage.getItem("active_tab"))
) || {};
} catch (e) {
/*Ignore*/
}
return ls[key];
}
}
function saveToLS(key, value) {
if (global.localStorage) {
global.localStorage.setItem(
localStorage.getItem("active_tab"),
JSON.stringify({
[key]: value
})
);
}
}
-
布局的更改功能
Onchange function of layout
const onLayoutChange = (layout, layouts) => { saveToLS("layouts", layouts); console.log("onchange"); setlayouts({ layouts }); };
编辑/更新
我已经更新了我的代码沙箱,因为它以前在控制台ans
undefined
上进行布局,现在在进行布局,这是更新的代码沙箱I have updated my code sandbox as earlier it was taking layouts on console ans
undefined
now it is taking the layout, Here is the updated code sandbox推荐答案
对于每个
active_menu
,该解决方案运行generateDOM
一次:The solution is run
generateDOM
once for eachactive_menu
:const [DOM, setDOM] = useState(null) useEffect(() => { setDOM(generateDOM(data1[active_menu].comp_data)) }, [data1, active_menu]);
data1
也应该是依赖项,因为添加和删除元素时需要重新计算"DOM"
.data1
should also be in dependencies because need to recalculate"DOM"
when adding and removing elements.渲染:
<ResponsiveReactGridLayout {...props} onLayoutChange={(layout, layouts) => onLayoutChange(layout, layouts)} layouts={layouts} cols={{ lg: 12, md: 4, sm: 6, xs: 4, xxs: 2 }} > {DOM} </ResponsiveReactGridLayout>
我也将
localStorage.getItem("active_tab")
更改为active_menu
这篇关于无法将我的React应用程序的布局存储在本地存储中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!