index.jsx
require ( './app/lib/common.css' ) ;
import React from 'react' ;
import ReactDOM from 'react-dom' ;
import ReduxApp from './reduxApp.js'
import { store } from './redux/store.js'
import { Provider } from 'react-redux'
ReactDOM. render (
< Provider store= { store} >
< ReduxApp / >
< / Provider> ,
document. getElementById ( 'myApp' )
)
reduxApp.js
import React from 'react'
import { increment, decrement, incrementAsync } from './redux/actions.js'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
class Reduxapp extends React. Component {
constructor ( props) {
super ( props)
this . increment = this . increment. bind ( this )
this . decrement = this . decrement. bind ( this )
this . incrementAsync = this . incrementAsync. bind ( this )
}
increment ( ) {
const number = this . select. value * 1
this . props. increment ( number)
}
decrement ( ) {
const number = this . select. value * 1
this . props. decrement ( number)
}
incrementAsync ( ) {
const number = this . select. value * 1
this . props. incrementAsync ( number)
}
render ( ) {
const count = this . props. count
return (
< div>
< h1> click { count} times< / h1>
< div>
< select ref= { select => this . select = select} >
< option value= '1' > 1 < / option>
< option value= '2' > 2 < / option>
< option value= '3' > 3 < / option>
< / select>
< button onClick= { this . increment} > + < / button>
< button onClick= { this . decrement} > - < / button>
< button onClick= { this . incrementAsync} > async < / button>
< / div>
< / div>
)
}
}
Reduxapp. propTypes = {
count: PropTypes. number. isRequired,
increment: PropTypes. func. isRequired,
decrement: PropTypes. func. isRequired,
incrementAsync: PropTypes. func. isRequired
}
export default connect (
state => ( { count: state} ) ,
{ increment, decrement, incrementAsync}
) ( Reduxapp)
store.js
import { createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
import { counter} from './reducers.js'
export const store = createStore ( counter, applyMiddleware ( thunk) )
reducers.js
import { INCREMENT , DECREMENT } from './action-types'
export function counter ( state= 0 , action) {
switch ( action. type) {
case INCREMENT :
return state+ action. data;
case DECREMENT :
return state- action. data;
default :
return state
}
}
actions.js
import { INCREMENT , DECREMENT } from './action-types.js'
export const increment = ( number) => (
{
type: INCREMENT , data: number
}
)
export const decrement = ( number) => (
{
type: DECREMENT , data: number
}
)
export const incrementAsync = ( number) => {
return dispatch => {
setTimeout ( ( ) => {
dispatch ( increment ( number) )
} , 1000 )
}
}
action-types.js
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'