component1javascript
component2java
reduxreact
export function increment(){ return { type: "+" } } export function decrement(){ return { type: '-' } }
export default (state = 0, action) => { switch(action.type){ case '+': return state + 1; case '-': return state - 1; default: return state; } }
import React, {Component} from 'react' import {connect} from 'react-redux' import * as Actions from './actions' import Component2 from '../cp2/cp2' class Component1 extends Component{ increment = () => { console.log(this.props) this.props.increment(); } render(){ return ( <div> <h3>component-cp1-{this.props.cp1}</h3> <input type="button" value="increment" onClick={this.increment}/> <Component2 /> </div> ) } } const mapStateToProps = (store) => { return { cp1: store.cp1 } } export default connect(mapStateToProps, Actions)(Component1)
export function increment(){ return { type: "+" } } export function decrement(){ return { type: '-' } }
export default (state = 0, action) => { switch(action.type){ case '+': return state + 1; case '-': return state - 1; default: return state; } }
import React, {Component} from 'react' import {connect} from 'react-redux' import * as Actions from './actions' class Component2 extends Component{ render(){ return ( <div> <h3>component-cp2-{this.props.cp2}</h3> </div> ) } } const mapStateToProps = (store) => { return { cp1: store.cp1, cp2: store.cp2 } } export default connect(mapStateToProps, Actions)(Component2)
import {createStore} from 'redux'; import { combineReducers } from 'redux'; import cp1 from '../components/cp1/reducer' import cp2 from '../components/cp2/reducer' const rootReducer = combineReducers({ cp1, cp2 }); const store = createStore(rootReducer) export default store;
import React from 'react' import ReactDOM from 'react-dom' import {Router, hashHistory} from 'react-router' import {Provider} from 'react-redux' import store from './redux/configStore' import Component1 from './components/cp1/cp1' ReactDOM.render( <Provider store={store}> <Component1/> </Provider>, document.getElementById('app') )
react-redux.connet
將state
和action
所有合併到了props
中去connet
第一個參數爲一個方法,該方法的第一個參數就是store
,也就是經過redux.combineReducers
來進行合併獲得一個rootReducer
react-redux.Provider
組件,其屬性store
就是經過redux.createStore
出來的store
props
調用actions
時,redux
隱性調用了store.dispath
,而不用手動去調用。reducer
中返回的值,也會傳到mapStateToProps
的參數當中去,而不用再手動調用store.getState()