【发布时间】:2018-12-13 19:33:49
【问题描述】:
首先,感谢您阅读我的问题并尝试帮助我并为我的英语道歉。
我正在尝试使用 React 在 Redux 上创建一个方法来改变层的可见性。
我的问题是更改可见性完美,但是当所有图层都不可见并尝试将它们更改为可见时,它们的 before 属性未定义,除了最后一个更改。
我会用一个例子更好地解释我。
mapLayers 是一个包含 3 层的数组:
- [2]第三层
- 1Layer2
- [0] 层 1
案例 1:
如果我隐藏Layer1,他的前属性未定义,现在我显示Layer1,现在他的前属性ID 为Layer2。
我的问题:
- [2]第三层
- 1Layer2
- [0] 层 1
3 层是不可见的,所以:
- 将
Layer2更改为可见 -> before = undefined - 将
Layer3更改为可见 -> before = undefined - 将
Layer1更改为可见 -> before = id of Layer2
但是当将 Layer3 更改为可见时(在第 2 步中), before 应该是未定义的,之后,当 Layer2.. before 的 Layer3 的可见性应该是 Layer2 id。
重要的是知道我正在使用 react-mapbox-gl,并且我需要在属性之前移动和隐藏/显示图层。
before: string 传递一个图层的id,会在id定义的图层之前显示当前图层。
https://github.com/alex3165/react-mapbox-gl/blob/master/docs/API.md
这是我的代码:
static changeLayerVisibility(layer) {
let mapLayers = [... AxisStore.getStore().getState().map.mapGLlayers];
const ids = mapLayers.map(l => l.id);
const index = ids.indexOf(layer.id);
const newVisibility = (layer.layout.visibility === 'visible') ? 'none' : 'visible';
let nextVisibleLayer = mapLayers.find((layerObj, idx) => idx > index && layerObj.layout.visibility === 'visible');
let updateLayout = Object.assign({}, mapLayers[index], {
layout: Object.assign({}, mapLayers[index].layout, { visibility: newVisibility }),
paint: Object.assign({}, mapLayers[index].paint),
before: newVisibility === 'visible' && nextVisibleLayer ? nextVisibleLayer.id: undefined
});
mapLayers.splice(index, 1, updateLayout);
return (dispatch) => {
dispatch({
type: MapTypeConstants.SET_MAP_LAYERS,
payload: mapLayers
});
};
}
【问题讨论】:
标签: javascript reactjs mapbox mapbox-gl-js