我刚刚开始一项新工作并且我有一些React代码需要维护,有一个名为authenticationHandlers.js
的文件,这就是代码在文件中的样子。
const events = require("./authenticationEvents.js");
const authenticationHandlers = {
[events.Errored.Name](prev, event) {
const update = {
UnauthorizedError: event.Error
};
return Object.assign({}, prev, update);
},
[events.ClearError.Name](prev, event) {
const update = {
UnauthorizedError: null
};
return Object.assign({}, prev, update);
}
};
module.exports = authenticationHandlers;
我对代码的功能没有任何疑问,但括号语法在第[events.Erorred.Name]
行和[events.ClearError.Name]
换句话说,括号是什么意思?
答案 0 :(得分:5)
您可以将变量用作属性名称:
例如:
const a = 'banana';
const fnName = 'pudding';
const b = {
[a]: 42,
[fnName]() {
console.log(`I am logging from ${fnName}`);
}
};
console.log(b); //{banana: 42, pudding: fn}
b[fnName]();

答案 1 :(得分:2)