json - 我想导入一个 JSON 文件,并在此过程中使用 JSON 文件中包含的处理函数。
问题描述
我似乎找不到将 JSON 的值转换为函数引用的方法。需要帮忙?
我附上了一个小代码片段供参考
//addButton.json
"row": [
{
"type": "button",
"name": "Add",
"label": "add",
"color": "warning",
"size": "lg",
"colsize": "3",
"onButtonClick": "this.handleAddRequest"
}
]
// CustomForm.jsx
import addBankApiInfoPage from '../addBankApiInfo.json';
class CustomForm extends React.Component{
handlerFunction = ()=>{
this.map.rowData(row=>{
if (rowData[row].startsWith("this.")) {
rowData[row] = eval("this" + r[k].substring(4, r[k].length));
}
});
}
运行此代码会引发错误
Uncaught TypeError: Cannot read property 'handleAddRequest' of undefined
at eval (eval at <anonymous> (Add.jsx:57), <anonymous>:1:6)
at Add.jsx:57
at Array.map (<anonymous>)
at Add.jsx:48
at Array.map (<anonymous>)
at Add.jsx:45
at Array.map (<anonymous>)
at new Add (Add.jsx:3
解决方案
1) 箭头函数不绑定this
您的问题几乎可以肯定是箭头函数没有将包含对象绑定到this
.
class Good {
meth(){return this}
}
class Good {
meth: function self(){return this}
}
class Bad {
meth: ()=>{return this} //will be undefined
}
2) 做没有意义eval
。
没必要做eval("this" + r[k].substring(4, r[k].length))
eval
应尽可能避免你已经有
"this"
作为字符串的一部分if
.substring
(or.slice
) 没有第二个参数到达字符串的末尾
在许多生产环境eval
中甚至不可用,因为它是安全漏洞的常见原因,并且性能和工具也很差。在您的情况下,如果您想引用正在运行的代码this
,您可以这样做
if (rowData[row].startsWith("this.")) {
rowData[row] = this[r[k].substring(4)]
}
如果您想要一个绑定到this
目标的方法,然后您可以从任何地方调用,而不仅仅是该参数中的函数,您可以通过以下两种方式之一绑定它:
if (rowData[row].startsWith("this.")) {
rowData[row] = this[r[k].substring(4)].bind(this)
}
// OR
if (rowData[row].startsWith("this.")) {
rowData[row] = () => this[r[k].substring(4)] // the `handlerFunction`'s `this` is captured by the closure
}
PS:甚至.bind
不能放入this
箭头功能。
console.log((()=>this).bind(1)())
VM3283:1 Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
console.log((function(){return this}).bind(1)())
VM3362:1 Number {1}