S
S
Stepan2015-11-30 18:50:52
React
Stepan, 2015-11-30 18:50:52

Explain in simple terms how Redux works?

Explain in simple terms. And I don't fully understand what's what.
Although I made a test application according to the manual

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
Nikita Gushchin, 2015-11-30
@iNikNik

You have one big tree that stores the entire state of the application - this is the store.
You also have a set of reducers (which are combined into one common rootReducer) - these are functions that take the current state and action and return the new state:

function someReducer(state = initialState, action) {
  // обычно выглядит как switch 
  // action - простой js-объект
  //              и обязательно имеет строковое поле type
  switch(action.type) {
    // обрабатываем действие с типом SOME_ACTION_NAME
    case 'SOME_ACTION_NAME':
      // берем какие-то данные из экшена и возвращаем новое состояние
      // при этом менять sate нельзя!
      // state.someProperty = action.newStateData <--- НЕТ!
      return { ...state, action.newStateData };
    // Если мы не обрабатываем действие - просто возвращаем старое состояние
    default:
      return state;
  }
}

There are also action creators (actionCreators) - these are functions that return an action. then this action is broadcast to the storage (dispatched). Typical example:
function someActionCreator(someArg) {
  return {
    type: 'SOME_ACTION_NAME',
    newStateData: someArg + 5, // <-- разная логика
  };
}

By default, we can only return a simple object as an action, but when creating a store, we can add the so-called middleWare. These are special functions that accept all actions from the dispatcher and can pass them on (while containing additional logic).
If we want to access the state in the action creator, we can use thunkMiddleware:
import thunkMiddleware from 'redux-thunk';

function createStore(initialState) {
  const reducer = combineReducers(reducers);
  const finalCreateStore = applyMiddleware(
    thunkMiddleware // <-- добавляем middleware
  )(defaultCreateStore);
  return finalCreateStore(reducer, initialState);
}

Now we can do this:
function someActionCreator(someArg) {
  return (dispatch, getState) => { // <-- возвращаем фукнцию, а не объект!
    const someState = getState().reducerName;
    return {
      type: 'SOME_ACTION_NAME',
      newStateData: someArg + someState, 
    };
  };
}

In general, the scheme looks like this:
We then take the connect method from react-redux , which connects your smart component to the store:
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

class MyComponent extends Component {
  static propTypes = {
    someProp: PropTypes.string.isRequired,
    someFunc: PropTypes.func.isRequired,
  };
}

// Тут мы берем из глобального состояния необходимую нам часть
// В ownProps - свойства компонента. Тут могут быть например свойства от роутера
function mapStateToProps(state, ownProps) {
  return {
    someProp: state.someReducer,
  };
}

function mapActionsToProps(dispatch) {
  return bindActionCreators ({ // <-- биндим все на disptach для удобства
    someFunc: (someArg) => someActionCreator(someArg + 1),
  }, dispatch);
}

export default connect(
  mapStateToProps,
  mapActionsToProps
)(MyComponent);

A
Andrey Antropov, 2015-11-30
@Laiff

An excellent manual from Dani himself https://egghead.io/series/getting-started-with-redux
Documentation translated into Russian https://github.com/rajdee/redux-in-russian almost everything is there.
There is also a nice article on Habré purely on basic principles, but in some places it is not complete habrahabr.ru/post/269831

M
mistbow, 2016-08-19
@mistbow

This helped me a lot, especially the pictures below...
https://medium.com/russian/a-cartoon-intro-to-redu...

L
loki_lo, 2017-05-12
@loki_lo

getinstance.info/articles/react/learning-react-redux

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question