Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
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;
}
}
function someActionCreator(someArg) {
return {
type: 'SOME_ACTION_NAME',
newStateData: someArg + 5, // <-- разная логика
};
}
import thunkMiddleware from 'redux-thunk';
function createStore(initialState) {
const reducer = combineReducers(reducers);
const finalCreateStore = applyMiddleware(
thunkMiddleware // <-- добавляем middleware
)(defaultCreateStore);
return finalCreateStore(reducer, initialState);
}
function someActionCreator(someArg) {
return (dispatch, getState) => { // <-- возвращаем фукнцию, а не объект!
const someState = getState().reducerName;
return {
type: 'SOME_ACTION_NAME',
newStateData: someArg + someState,
};
};
}
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);
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
This helped me a lot, especially the pictures below...
https://medium.com/russian/a-cartoon-intro-to-redu...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question