我有一个反应网格布局,并且正在使用 redux 来管理我的网格元素的状态。我可以添加包含我想要的内容的网格项目,它们可以在网格周围移动并按照我想要的方式调整大小。问题是当我更改网格大小或位置时,它不会更新 redux 存储中的状态,因此当我离开仪表板页面并返回它时,网格对象会重置为其初始状态。我想使用一个动作来更新布局,并尝试在下面的庄园中这样做,尽管当我尝试控制台记录我的布局时,我发现它没有更新。
这是我的减速器,包括 addItem:
const initialState = {
layout: [],
count:[],
};
const reducer = (state=initialState, action) => {
switch (action.type) {
case actionTypes.ADD_GRID_ITEM:
const id = uuid()
console.log("adding: " + id)
return{
...state,
count: state.count.concat(<CreateGraph/>),
layout: state.layout.concat({
i: `${id}`,
x: 2,
y: 0,
w: 4,
h: 5
}),
}
case actionTypes.UPDATE_LAYOUT:
const updateLayout = (key, value) => {
Object.assign(
{},
state,
{
[key]: value,
},
);
}
return {
...state,
updateLayout
}
}
return state;
}
export default reducer;
这是我的反应网格布局的代码。我想在每次更改布局时更新布局 - 这可以使用 onLayoutChange 属性来完成。
const ReactGridLayout = WidthProvider(Responsive);
const Dash = (props) => {
const layout = props.layout
const { value, addItem, updateLayout } = props
const ref = useRef()
const onLayoutChange = (layout, layouts) => {
props.updateLayout("layouts", layouts)
console.log(...props.layout)
}
return (
<div>
<button onClick={addItem}>Add Item</button>
<ReactGridLayout
{...props}
className="layout"
layouts={props.layout}
onLayoutChange={(layout, layouts => onLayoutChange(layout, layouts))}
breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
resizeHandles={['s', 'w', 'e', 'n', 'sw', 'nw','se', 'ne']}
verticalCompact={false}
draggableHandle=".dragHandle"
>
{_.map(value, (item, i) => (
<div id = 'gridID' ref={ref} key={i} data-grid={props.layout[i]}>
<span className='dragHandle'>Drag From Here</span>
<br/>
<DashItem key={i} >
{item}
</DashItem>
<span className='dragHandle'>Drag From Here</span>
</div>
))}
</ReactGridLayout>
</div>
);
}
Dash.propTypes = {
value: PropTypes.array,
onIncreaseClick: PropTypes.func.isRequired
}
const mapStateToProps = (state) => {
return {
value: state.count,
layout: state.layout,
onLayoutChange: state.onLayoutChange,
};
};
const mapDispatchToProps = dispatch => {
return {
addItem: () => dispatch({type: actionTypes.ADD_GRID_ITEM}),
updateLayout: (key, value) => dispatch({type: actionTypes.UPDATE_LAYOUT, key, value})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Dash);