Create a gist now

Instantly share code, notes, and snippets.

React Redux連携サンプル
import * as types from '../constants.js';
export const increment = () => ({ type: types.INCREMENT });
export const decrement = () => ({ type: types.DECREMENT });
export const rename = (name) => ({ type: types.RENAME, name: name });
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import React from 'react';
import * as Actions from '../actions';
import Hoge from '../components/hoge';
class App extends React.Component {
render() {
const props = this.props;
return (<div>
<Hoge {...props}/>
<button onClick={() => this.props.increment()}>増加</button>
</div>);
}
}
function mapStateToProps(state) {
return state;
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(Actions, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export const RENAME = 'RENAME';
import React, { Component, PropTypes } from 'react'
export default class Hoge extends React.Component {
render() {
return (<div>
<div>{this.props.name}: {this.props.count}</div>
<button onClick={() => this.props.increment()}>増加</button>
<button onClick={() => this.props.decrement()}>減少</button>
<input type="text" onChange={(e) => this.props.rename(e.target.value)} value={this.props.name} />
</div>);
}
}
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import React from 'react';
import App from './containers/App';
import reducer from './reducers';
const store = createStore(reducer);
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app'),
);
import * as types from '../constants.js';
const initialState = {
count: 0,
name: 'ほげ'
};
export default (state = initialState, action) => {
switch (action.type) {
case types.INCREMENT:
return Object.assign({}, state, { count: state.count + 1 });
case types.DECREMENT:
return Object.assign({}, state, { count: state.count - 1 });
case types.RENAME:
return Object.assign({}, state, { name: action.name });
default:
return state;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment