javascript - react JS : Refactoring Redux Selectors

标签 javascript reactjs redux react-redux selector

我正在使用多个选择器来获取设置 Google map 的边界。它们基本上返回数据中的最低和最高纬度/经度点。该代码可以工作,但我觉得这真的很困惑,可以重构,但我不太确定如何重构。

这是代码:

const getMinLat = data =>
  data.reduce((prev, current) => {
    return prev.coords[0] < current.coords[0] ? prev : current
  })

const getMaxLat = data =>
  data.reduce((prev, current) => {
    return prev.coords[0] > current.coords[0] ? prev : current
  })

const getMinLng = data =>
  data.reduce((prev, current) => {
    return prev.coords[1] < current.coords[1] ? prev : current
  })

const getMaxLng = data =>
  data.reduce((prev, current) => {
    return prev.coords[1] > current.coords[1] ? prev : current
  })

const getBounds = data => [
  {
    lat: getMinLat(data).coords[0],
    lng: getMinLng(data).coords[1],
  },
  {
    lat: getMaxLat(data).coords[0],
    lng: getMaxLng(data).coords[1],
  },
]

最佳答案

只需遍历列表一次:

const getBounds = data => 
    data.reduce(
        ([
             {lat: minLat, lng: minLng}, 
             {lat: maxLat, lng: maxLng}
         ], 
         {coords: [lat, lng]}
        ) =>
       [
            {
                lat: Math.min(minLat, lat), 
                lng: Math.min(minLng, lng)
            }, 
            {
                lat: Math.max(maxLat, lat), 
                lng: Math.max(maxLng, lng)
            }
      ], 
      [{lat: Infinity, lng: Infinity}, {lat: -Infinity, lng: -Infinity}]
    )

我事先同意,可读性并不是这里的优势。但它只遍历列表一次。

此外,在习惯了解构语法之后,很明显,Math.maxmaxLng/maxLat 结合在一起可以减少使用错误变量的可能性

[UPD]并且不需要使用Infinity/-Infinity作为起始值(我用它们来突出背后的想法)。对于经度/纬度,我们可以使用 180/-180 作为最极端的值

关于javascript - react JS : Refactoring Redux Selectors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53447632/

相关文章:

reactjs - 如何在 react 中传递传播运算符中的多个 Prop

javascript - react 未捕获的 DOMException : Failed to execute 'createElement' on 'Document' : The tag name provided ('<div>' ) is not a valid name

reactjs - 当 Redux 状态更改为低于第一级别时,React 不会更新

javascript - NextJS 凭证自定义登录重定向到默认表单

javascript - Heroku 应用程序无法运行(部署问题?)

reactjs - Material 表标题 react 中的 Col span 和 Row span

reactjs - 如何将 store 作为 prop 显式传递给 "Connect()"

reducers - 使用拆分 reducer 更新相关状态字段的最佳方法?

javascript - 使用 Angular Material 展开折叠列表项

javascript - Node 环境和浏览器中的等效 GET 请求未显示相同的结果