This Gist was automatically created by Carbide, a free online programming environment.
Last active
March 3, 2017 16:33
-
-
Save carbide-public/26802b756d894a5aadb12f54f2f09c85 to your computer and use it in GitHub Desktop.
React redux redux-act
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import { connect } from 'react-redux' | |
import { COUNTER } from './cell2' | |
class Button extends Component { ///Класс кнопки с props click и name | |
constructor() { | |
super() | |
this.render = this.render.bind(this) ///Стандартный ритуал привязки функций если нет babel class property | |
} | |
render(){ | |
return <button onClick={this.props.click}>{this.props.name}</button> | |
} | |
} | |
function incDispatchToProps(dispatch) { ///Создаём варианты кнопок, это функци для общения со стором с помощью dispatch и выполнения наших action-creators | |
return { | |
click: () => dispatch(COUNTER.INCREMENT()) | |
} | |
} | |
function resetDispatchToProps(dispatch) { | |
return { | |
click: () => dispatch(COUNTER.RESET()) | |
} | |
} | |
export const ResetButton = connect(null,resetDispatchToProps)(Button) | |
export const IncButton = connect(null,incDispatchToProps)(Button) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createReducer } from 'redux-act' | |
import { combineReducers } from 'redux' | |
import { COUNTER } from './cell2.js' | |
const counter = createReducer({ ///Модель counter, на каждый экшн у нас своя реакция. Фича в том, что все такие модели могут реагировать на любые экшны по своему | |
[COUNTER.INCREMENT]: state => state+1, | |
[COUNTER.RESET] : () => 0, | |
[COUNTER.RANGE] : (state, payload) => | |
state > payload | |
? payload | |
: state | |
}, 0) ///Вторым аргументом обязательно передаём значение для поля по умолчанию | |
export default counter |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createAction } from 'redux-act' | |
///Список action creator в одном месте. Никаких type и payload, просто описываем какие экшны будем создавать\\Получаются объекты с функциями action creators и читаемыми именами в redux dev tools | |
export const COUNTER = { | |
INCREMENT: createAction('Обновление счётчика'), | |
RESET : createAction('Сброс счётчика'), | |
RANGE : createAction('Установка верхней границы') | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createReducer } from 'redux-act' | |
import { combineReducers } from 'redux' | |
import { COUNTER } from './cell2' | |
const history = createReducer({ | |
[COUNTER.INCREMENT]: state => [...state, 'inc'], ///[...state, 'inc'] значит что мы иммутабельно добавляем в массив ещё один элемент | |
[COUNTER.RESET] : state => [...state, 'reset'], | |
[COUNTER.RANGE] : state => [...state, 'range'] | |
}, ['reset']) | |
const last = arr => arr[arr.length-1] | |
const valuesLog = createReducer({ /// Любая модель может реагировать на любое количество экшнов, не обязательно на все сразу | |
[COUNTER.INCREMENT]: state => [...state, last(state)+1 ], | |
[COUNTER.RESET] : state => [...state, 0 ] | |
}, [0]) | |
const log = combineReducers({ ///Собраем один сложный объект для стора из нескольких простых\\log: {\\ values: [0, 1, 2, 0, 0 ],\\ commands: [ 'reset', 'inc', 'inc'. 'reset', 'reset']\\} | |
values, | |
commands | |
}) | |
export default log |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createStore, combineReducers } from 'redux' | |
import log from './cell3' | |
import counter from './cell1' | |
const storeModel = combineReducers({ ///Так выглядит корень redux стора | |
counter, | |
log | |
}) | |
const store = createStore(storeModel) ///Создаём стор и экспортируем | |
export default store |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Provider } from 'react-redux' | |
import React from 'react' | |
import ReactDOM from 'react-dom' | |
import { ResetButton, IncButton } from './cell0' | |
import Label from './cell6' | |
import store from './cell4'; | |
ReactDOM.render( | |
<Provider store={store}> | |
<div> | |
<ResetButton name='reset' /> | |
<IncButton name='+1' /> | |
<Label /> | |
</div> | |
</Provider> | |
,document.getElementById('root') | |
) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import { connect } from 'react-redux' | |
class Label extends Component { | |
constructor() { | |
super() | |
this.render = this.render.bind(this) | |
} | |
render(){ | |
return <span>Counts: {this.props.text} History size: {this.props.size}</span> | |
} | |
} | |
function stateToProps(state) { ///Эта функция для привязки значений стора к данным, отображение будет реагировать на его изменения | |
return { | |
text: state.counter, | |
size: state.log.commands.length | |
} | |
} | |
export default connect(stateToProps)(Label) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment