Internet Explorer 和 ReactJS 的 Object.entries() 替代方法

15

好的,我已经建立了一个网络应用程序几周了,一切都很顺利。我到了必须在Internet Explorer中进行测试的部分,所有的问题都解决了(除了一个),Object.entries()不被支持。

我做了一些研究并尝试找到一个简单的替代方法,但完全没有运气。

更具体地说,我正在从API中获取一个对象,以填充<select></select>字段的选项,我需要过滤一些信息,就像这样:

Object.entries(this.state.filterInfo.sectorId).map(this.eachOption)

// Function
eachOption = ([key, val], i) => {
    return(
        <option value={val} key={i}>{val}</option>
    );
}

一切都正常工作,除了Internet Explorer浏览器。问题是在这个特定的组件中,我正在渲染超过30个<select></select>字段。如果没有需要我重建所有内容的解决方案,那将太棒了。

有简单的解决方案吗? 有什么方法可以避免这种情况吗?

提前感谢。


1
你有尝试过加载polyfill吗?这是解决缺失函数的标准方法。 - loganfsmyth
3
这个 "polyfill" 相当简单。 - Bergi
1
Object.keys(this.state.filterInfo.sectorId).map(this.eachOption,this.state.filterInfo.sectorId) 其中在回调函数中,您可以通过 this[key] 获取值。 - dandavis
2
文档中显示了一个 polyfill。链接 - Barmar
5个回答

32

当你想在旧浏览器中使用新的API时,通常需要研究的第一件事是是否有一个简单的polyfill。确实,在MDN文档站点上展示了一个相当简单的Object.entries() polyfill:

if (!Object.entries)
  Object.entries = function( obj ){
    var ownProps = Object.keys( obj ),
        i = ownProps.length,
        resArray = new Array(i); // preallocate the Array
    while (i--)
      resArray[i] = [ownProps[i], obj[ownProps[i]]];

    return resArray;
  };

3

以上答案没有必要新的东西,只是用不同的代码完成同样的事情。

希望这对任何碰巧遇到这个问题的人有所帮助。

// Another approach

const entriesPolyFill = (obj) => Object.keys(obj).map(key => [key, obj[key]]);


// Same thing but easier to read

function entriesPolyFill(obj) {
    const keys = Object.keys(obj);

    const keyValuePairs = keys.map(key => {
        const value = obj[key];
        
        return [key, value];
    });
    
    return keyValuePairs;
 };
 
 
// Possible usage if you don't want to alter Object class:
// Ex: Need key-value pairs to iterate over
const entries = (Object.entries ? Object.entries(obj) : entriesPolyFill(obj));

// Then do whatever you want with the Array
// ---> entries.map(), entries.filter(), etc..

// You could also move the whole thing to a function
// and always call the function so you don't have to
// write excess ternary operators in your code:

// -- In a utils file somewhere else...
export function getEntries(obj) {
  return Object.entries ? Object.entries(obj) : Object.keys(obj).map(key => [key, obj[key]]);
}

// Wherever you need to get entries in you project
import { getEntries } from "<path to utils>";

...

const entries = getEntries(obj);


3
import 'core-js/es7/object';

对我来说这个有效。


在 Angular CLI 生成的项目中,pollyfills.ts 默认添加了 "core-js/es6/object",但实际上这个代码并没有被执行,而是使用了其他代码。 - AC101
我不得不添加 import 'core-js/es/object'; 才能使它正常工作。 - schlonzo

1

这是一个简洁的 polyfill,它巧妙地使用了 Array.prototype.reduce

if(!Object.entries) 
    Object.entries = function(obj) {
        return Object.keys(obj).reduce(function(arr, key) {
            arr.push([key, obj[key]]);
            return arr;
        }, []);
    }

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接