简体   繁体   English

React 中的 for 循环显示 ESLint 错误

[英]The for loop in React showing ESLint error

The for loop inside the objToQueryString function showing me the error objToQueryString 函数内的 for 循环向我显示错误

ESLint: The body of a for-in should be wrapped in an if statement to filter unwanted properties from the prototype.(guard-for-in) ESLint:for-in 的主体应该包含在 if 语句中,以过滤原型中不需要的属性。(guard-for-in)

const objToQueryString = obj => {
  const keyValuePairs = [];
  for (const key in obj) {
    keyValuePairs.push(
      `${encodeURIComponent(key)}${encodeURIComponent(
        `: "`
      )}${encodeURIComponent(obj[key])}`
    );
  }
  return `${encodeURIComponent(`{`)}${keyValuePairs.join(
    encodeURIComponent(`", `)
  )}${encodeURIComponent(`" }`)}`;
};

And adding this: // eslint-disable-next-line guard-for-in is not working并添加: // eslint-disable-next-line guard-for-in不起作用

Wrap your push statement with

const objToQueryString = (obj) => {
  const keyValuePairs = [];
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      keyValuePairs.push(
        `${encodeURIComponent(key)}${encodeURIComponent(
          ': "',
        )}${encodeURIComponent(obj[key])}`,
      );
    }
  }
  return `${encodeURIComponent('{')}${keyValuePairs.join(
    encodeURIComponent('", '),
  )}${encodeURIComponent('" }')}`;
};

More on the rule details and explanation here更多关于规则的细节和解释在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM