简体   繁体   中英

Implementing Redux Store from Scratch

I am following a Redux tutorial series . In that Dan Abramov shows how to create a Redux store from scratch. Here's that piece of code

const createStore = (reducer) => {
 let state;
 let listeners = [];

 const getState = () => state;

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

 const subscribe = (listener) => {
   listeners.push(listener);
   return () => {
     listeners = listeners.filter(l => l !== listener());
   };
 };

 dispatch({});

 return {getState, dispatch, subscribe};
}

The following line inside the dispatch function is what I am confused about,

listeners.forEach(listener => listener());

I know that it iterates through all the elements in the listeners array & passes each element to the arrow function.

But what does this do listener()

listeners is an array of functions so listeners.forEach(listener => listener()); iterates through the listener functions and invokes them with listener() .

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