如何解决 Array.sort 无法分配给对象的只读属性“0”的问题

Jak*_*kub 5 javascript reactjs

在我的 React 应用程序中,我在排序功能中遇到错误

\n

Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]'

\n

我不知道问题是什么,功能是这样的:

\n
const preparedSites = useMemo(\n      () =>\n        sites\n          .sort(sortSiteSelection(site))\n          .map(elm => {\n            const arr = [\n              elm.siteId,\n              elm.city,\n              elm.state,\n              elm.country,\n              elm.address,\n              elm.status,\n            ];\n            if (nearestSites.length)\n              arr.push(\n                nearestSites.find(s => s.closestSiteId === elm.siteId).distance,\n              );\n            return arr;\n          })\n          .sort((a, b) => a[6] - b[6]),\n      [sites, site, nearestSites],\n    );\n
Run Code Online (Sandbox Code Playgroud)\n

零件和 \xc2\xb4sortSiteSelection\xc2\xb4上发生的错误.sort如下

\n
const nameCompare = (x, y) => x.name.localeCompare(y.name);\nconst cityCompare = (x, y) => x.city.localeCompare(y.city);\nconst compareCountry = s => (x, y) => {\n  if (!s) return 0;\n\n  if (x.countryCode === s.countryCode && y.countryCode === s.countryCode)\n    return 0;\n  else if (x.countryCode === s.countryCode) return -1;\n  else if (y.countryCode === s.countryCode) return 1;\n  else return x.countryCode.localeCompare(y.countryCode);\n};\n\nexport const sortSiteSelection = selectedSite => {\n  if (!selectedSite) {\n    console.log('NULL FROM SORT SITE');\n    return () => 0;\n  }\n  pipeSort(compareCountry(selectedSite), nameCompare, cityCompare);\n};\n
Run Code Online (Sandbox Code Playgroud)\n

网站的OBJ只是

\n
{\n siteId,\n city,\n elm.state,\n country,\n address,\n status,\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n

小智 21

我想说这是因为数组处于严格模式。您应该创建该数组的副本。有多种方法可以实现这一点。

[...sites].sort(sortSiteSelection(site))
Run Code Online (Sandbox Code Playgroud)

或者

sites.slice().sort(sortSiteSelection(site))
Run Code Online (Sandbox Code Playgroud)

我希望这能解决您面临的问题