如何避免 'eval' 在此反应组件中?
How to avoid 'eval' in this react component?
我正在使用 Gatsby 静态页面生成器来创建静态网站。我创建了一个这样的组件:
const Subject = ({data, location, pageContext) => {
const currentPage = eval("pagecontext.num" + (pageContext.queryfor) + "s")
return (
console.log(currentPage) //returns page number as expected
)
}
如您所见,我正在使用 eval
根据一些字符串和另一个变量构造一个变量。代码运行完美,正如预期的那样,但我收到警告:
warn ESLintError:
E:\Build\gatsby\src\components\subject.js
warning eval can be harmful no-eval
他们我读了一些关于如何永远不要使用 eval 的信息,因为它很危险。如何避免在我的代码中使用 eval
?谢谢。
只需使用 map:
let myMap = new Map();
myMap.set("pagecontext.num" + (pageContext.queryfor) + "s", VALUE_OF_THIS_VARIABLE)
...
// then access it like before:
const currentPage = myMap.get("pagecontext.num" + (pageContext.queryfor) + "s")
切换到bracket notation:
const Subject = ({data, location, pageContext) => {
const currentPage = pageContext[`num${pageContext.queryfor}s`])
return (
console.log(currentPage) //returns page number as expected
)
}
我正在使用 Gatsby 静态页面生成器来创建静态网站。我创建了一个这样的组件:
const Subject = ({data, location, pageContext) => {
const currentPage = eval("pagecontext.num" + (pageContext.queryfor) + "s")
return (
console.log(currentPage) //returns page number as expected
)
}
如您所见,我正在使用 eval
根据一些字符串和另一个变量构造一个变量。代码运行完美,正如预期的那样,但我收到警告:
warn ESLintError:
E:\Build\gatsby\src\components\subject.js
warning eval can be harmful no-eval
他们我读了一些关于如何永远不要使用 eval 的信息,因为它很危险。如何避免在我的代码中使用 eval
?谢谢。
只需使用 map:
let myMap = new Map();
myMap.set("pagecontext.num" + (pageContext.queryfor) + "s", VALUE_OF_THIS_VARIABLE)
...
// then access it like before:
const currentPage = myMap.get("pagecontext.num" + (pageContext.queryfor) + "s")
切换到bracket notation:
const Subject = ({data, location, pageContext) => {
const currentPage = pageContext[`num${pageContext.queryfor}s`])
return (
console.log(currentPage) //returns page number as expected
)
}