thi*_*ami 2 javascript destructuring ecmascript-6 redux-actions
我仔细阅读了redux-actions教程,并对他们使用(我相信的)解构感到困惑.下面是一个示例(increment&decrement是函数返回的createAction函数).
const { createAction, handleActions } = window.ReduxActions;
const reducer = handleActions(
{
[increment]: state => ({ ...state, counter: state.counter + 1 }),
[decrement]: state => ({ ...state, counter: state.counter - 1 })
},
defaultState
);
Run Code Online (Sandbox Code Playgroud)
这是另一个使用的例子:
const { createActions, handleActions, combineActions } = window.ReduxActions;
?
const reducer = handleActions(
{
[combineActions(increment, decrement)]: (
state,
{ payload: { amount } }
) => {
return { ...state, counter: state.counter + amount };
}
},
defaultState
);
Run Code Online (Sandbox Code Playgroud)
有人可以解释这些行中发生了什么吗?简单来说,我只是看到了{[function]: () => ({})},并且不明白这是做什么的.
这确实是一个计算属性名称,但有一个扭曲 - 一个函数用作键,而不是字符串.
在您记住每个函数都可以安全地转换为字符串之前,它可能看起来很混乱 - 结果就是该函数的源代码.这就是这里发生的事情:
function x() {}
const obj = { [x]: 42 };
console.log( obj[x] ); // 42
console.log( obj[x.toString()] ); // 42, key is the same actually
console.log( Object.keys(obj) ); // ["function x() {}"]
Run Code Online (Sandbox Code Playgroud)
这种方法的优点是你不需要创建额外的键 - 如果你有一个函数引用,你已经有了一个.事实上,你甚至不需要有一个引用 - 它足以拥有一个具有相同源的函数:
const one = () => '';
const two = () => '';
console.log(one === two); // false apparently
const fatArrObj = { [one]: 42 }
fatArrObj[two]; // 42, take that Oxford scholars!!
Run Code Online (Sandbox Code Playgroud)
缺点是函数在每次被用作键时被强制转换为字符串 - 一个(据称是次要的)性能损失.
为了增加一些乐趣,这是有效的对象文字:
{
[null]: null, // access either with [null] or ['null']
[undefined]: undefined,
[{ toString: () => 42 }]: 42 // access with, you guess it, 42 (or '42')
}
Run Code Online (Sandbox Code Playgroud)
......这个可能会进入奇怪的面试问题的书中:
const increment = (() => { let x = 0; return () => ++x })();
const movingTarget = { toString: increment };
const weirdObjectLiteral = { [movingTarget]: 42 };
console.log( weirdObjectLiteral[movingTarget] ); // undefined
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98 次 |
| 最近记录: |