排序问题(我想我只是搞乱了基本的ES6,但我没有看到它):
我有一个从状态进入的绘图对象数组(实际上,两个数组中的一个,取决于是否已应用过滤器。)每个对象都有一个GeoJSON功能作为属性。我还有一个来自州的地图中心物业。在MapStateToProps中,我定义了一个函数,它返回一个绘图距离地图中心的距离(验证它是否正常工作),然后另一个复制绘图数组,按照它们与中心的距离对绘图进行排序,然后返回新数组。但遗憾的是,新阵列没有正确排序(没有命令。)
有谁看到我错过了什么?
function mapStateToProps(state) {
const distancetoCenter = (shape, props) => {
if (shape.feature && props.mapCenter) {
const theDistance = distance(
centroid(shape.feature).geometry.coordinates.reverse(),
point([props.mapCenter.lat, props.mapCenter.lng]),
{ units: 'kilometers' }
);
//console.log(`the distance to center of ${shape.name} is ${theDistance}`);
return theDistance;
}
};
const sortPlots = props => {
if (props.filteredPlots || props.plots) {
return (props.filteredPlots || props.plots).slice(0).sort((a, b) => {
distancetoCenter(b, props) - distancetoCenter(a, props);
});
}
};
const sortedPlots = sortPlots(state.plots);
return {
mapCenter: state.plots.mapCenter,
sortedPlots
};
}
在.sort
回调中,您需要返回结果:
distancetoCenter(b, props) - distancetoCenter(a, props);
应该:
return distancetoCenter(b, props) - distancetoCenter(a, props);
另一种解决方案可能是省略arrow function中的花括号。然后返回表达式的结果。
return (props.filteredPlots || props.plots).slice(0).sort((a, b) =>
distancetoCenter(b, props) - distancetoCenter(a, props)
);