一个小例子 to play around React-Redux:
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux' let initialState = { count : 0, } function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return {...state, count: state.count + 1}; case 'DECREMENT': return {...state, count: state.count - 1}; default: return state; } } let store = createStore(reducer); const Message = function(props){ let _style = { margin:'100px auto', fontSize:'50px', textAlign:'center' } return ( <div style={_style}>Counter : {props.counter}</div> ); } class App extends React.Component{ constructor(props){ super(props); this.state = { counter : 0 } store.subscribe(() => { this.setState({counter: store.getState().count}); }); //this.increaseCounter = this.increaseCounter.bind(this); } increaseCounter = () => { store.dispatch({ type: 'INCREMENT' }); } decreaseCounter = () => { store.dispatch({ type: 'DECREMENT' }); } render(){ let _style = { margin:'0 auto', textAlign:'center' } return ( <div style={_style}> <Message counter={this.state.counter}/> <button onClick={this.increaseCounter}>Increment</button> <button onClick={this.decreaseCounter}>Decrement</button> </div> ) } } ReactDOM.render( <App /> , document.getElementById('root') );
以下是使用react-redux的方式,以作对比:
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore } from 'redux'; import { connect } from 'react-redux'; import { Provider } from "react-redux"; let initialState = { count : 0, } function reducer(state = initialState, action) { switch (action.type) { case 'INCREMENT': return {...state, count: state.count + 1}; case 'DECREMENT': return {...state, count: state.count - 1}; default: return state; } } let store = createStore(reducer); const Message = function(props){ let _style = { margin:'100px auto', fontSize:'50px', textAlign:'center' } return ( <div style={_style}>Counter : {props.counter}</div> ); } class App extends React.Component{ constructor(props){ super(props); } increaseCounter = () => { this.props.increment(); } decreaseCounter = () => { this.props.decrement(); } render(){ let _style = { margin:'0 auto', textAlign:'center' } return ( <div style={_style}> <Message counter={this.props.counter}/> <button onClick={this.increaseCounter}>Increment</button> <button onClick={this.decreaseCounter}>Decrement</button> </div> ) } } const mapStateToProps = (state) => { return { counter: state.count }; }; const mapDispatchToProps = (dispatch) => { return { increment:() => { dispatch({type:'INCREMENT'}); }, decrement:() => { dispatch({type:'DECREMENT'}); } } } //Just another higher order component to me: const AppWrap = connect(mapStateToProps,mapDispatchToProps)(App); ReactDOM.render( <Provider store={store}> <AppWrap /> </Provider> , document.getElementById('root') );