简体   繁体   中英

What listener() does in the Redux store?

I'm watching Dan Abramov's Redux videos on Egghead. In the video where he implements the Redux Store from scratch, he includes this code (around 1:28 - https://egghead.io/lessons/javascript-redux-implementing-store-from-scratch ):

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

So this code iterates through each item in the listener array, and I understand that each listener needs to be updated, but I don't get what listener() is doing. Where does this function come from?

createStore method have listeners variable. It is a array of functions which should be called when store updates. You can add own function into listeners through method subscribe method of store .

For example:

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

Function with console.log will be called after state will changed.

That syntax is called an arrow function and is new to ECMAScript 6. Without the special syntax, that code would look like this:

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

listener s is an array of functions. listeners is being iterated over with the Array.prototype.forEach function which takes a function as it's parameter.

'listener' in that context is the variable name given to the function passed into the lambda expression.

When the Array.prototype.forEach function invokes your function, it passes in the current item in the iteration. in this code that item is a function and it's just being invoked.

To put it simply, this code will iterate over an array of functions and invoke each one.

It might help to understand the API for the Array.prototype.forEach function. Here's the documentation:

Array.prototype.forEach

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

Arrow Functions

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

Listen is a method on the store that takes a handler. The handler is a function that when called causes the DOM to render:

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

The way I understand it is that the listeners array consists of the render function on different React components that are connected to the Redux store.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM