понедельник, 29 августа 2016 г.

React Redux Router My CheatSheet

// React Redux Router

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import {createStore, combineReducers, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import {Router, Route, hashHistory} from 'react-router';
import {syncHistoryWithStore, routerReducer, routerMiddleware, push} from 'react-router-redux';

function reducer (state = {name: 'Boris'}, action) {
    switch (action.type) {
        case 'CHANGE_NAME': return {name: action.name};
        default: return state;
    }
};

const reducers = combineReducers({
      user: reducer
    , routing: routerReducer
});

const initialState = {user: {name: 'Nick'}};

const store = createStore(reducers, applyMiddleware(routerMiddleware(hashHistory)));

const history = syncHistoryWithStore(hashHistory, store);

class App extends Component {
    render () {
        return (
            <div>Привет {store.getState().user.name} <a onClick={this.handleClick.bind(this)}>Измени имя</a> {this.props.children}</div>
        );
    }
    handleClick (event) {
        event.preventDefault();
        store.dispatch({type: 'CHANGE_NAME', name: 'Vova'});
        store.dispatch(push('/change_name'));
    }
}

class List extends Component {
    render () {
        return (
            <div>{store.getState().user.name}</div>
        );
    }
}

ReactDOM.render(
        <Provider store={store}>
            <Router history={history}>
                <Route path="/" component={App}>
                    <Route path="change_name" component={List} />
                </Route>
                <Route path="*" component={App} />
            </Router>
        </Provider>
    , document.getElementById('root')
);

Комментариев нет:

Отправить комментарий