2016-03-22 36 views
1

我正在看Egghead上的Dan Abramov's Redux视频。在那里他从无到有实现了终极版存储视频,他包含该代码(约1:28 - https://egghead.io/lessons/javascript-redux-implementing-store-from-scratch):Redux商店中的监听器()是什么?

const dispatch = (action) => { 
    state = reducer(state, action); 
    listeners.forEach(listener => listener()); 
}; 

所以这段代码遍历监听器阵列中的每个项目,据我所知,每个听众需要更新,但是我没有听到listener()在做什么。这个功能从哪里来?

回答

1

这句法被称为箭头功能,是新的ECMAScript 6.如果没有特殊的语法,该代码应该是这样的:

listeners.forEach(function(listener){ 
    return listener(); 
}); 

听众小号是一个函数数组。监听器正在使用Array.prototype.forEach函数进行迭代,该函数将函数作为参数。

在该上下文中的“侦听器”是传递给lambda表达式的函数的变量名称。

当Array.prototype.forEach函数调用您的函数时,它会传入迭代中的当前项目。在这段代码中,item是一个函数,它只是被调用。

简而言之,这段代码将迭代一个函数数组并调用每一个函数。

这可能有助于理解Array.prototype.forEach函数的API。这里的文档:

Array.prototype.forEach

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

箭头功能

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

1

createStore方法有listeners变量。这是应用程序存储更新时应调用的一组函数。 您可以通过方法subscribe方法store将自己的功能添加到listeners

例如:后状态会改变

console.log
const store = createStore(reducer); 
store.subsribe(state => console.log(state)); // add function into listeners 
store.dispatch(action); 

功能将被调用。

0

Listen是商店中的一个处理方法。该处理程序是一个函数,使调用时DOM来呈现:

store.listen(() => { 
 
    ReactDOM.render(
 
    <div>{JSON.stringify(store.getState(), null, 2)}</div>, 
 
    document.getElementById('root') 
 
); 
 
});

我理解的是,听众阵列由不同的渲染功能的阵营连接到组件的方式Redux商店。