多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
``` import React, { Component } from 'react' import PropTypes from 'prop-types' import ReactDOM from 'react-dom' import { createStore } from 'redux' import { Provider, connect } from 'react-redux' // React component class Counter extends Component { render() { const { value, onIncreaseClick } = this.props return ( <div> <span>{value}</span> <button onClick={onIncreaseClick}>Increase</button> </div> ) } } Counter.propTypes = { value: PropTypes.number.isRequired, onIncreaseClick: PropTypes.func.isRequired } // Action const increaseAction = { type: 'increase' } // Reducer function counter(state = { count: 0 }, action) { const count = state.count switch (action.type) { case 'increase': return { count: count + 1 } default: return state } } // Store const store = createStore(counter) // Map Redux state to component props function mapStateToProps(state) { return { value: state.count } } // Map Redux actions to component props function mapDispatchToProps(dispatch) { return { onIncreaseClick: () => dispatch(increaseAction) } } // Connected Component const App = connect( mapStateToProps, mapDispatchToProps )(Counter) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ) ``` 我们来看一个实例。下面是一个计数器组件,它是一个纯的 UI 组件。 ~~~javascript class Counter extends Component { render() { const { value, onIncreaseClick } = this.props return ( <div> <span>{value}</span> <button onClick={onIncreaseClick}>Increase</button> </div> ) } } ~~~ 上面代码中,这个 UI 组件有两个参数:`value`和`onIncreaseClick`。前者需要从`state`计算得到,后者需要向外发出 Action。 接着,定义`value`到`state`的映射,以及`onIncreaseClick`到`dispatch`的映射。 ~~~javascript function mapStateToProps(state) { return { value: state.count } } function mapDispatchToProps(dispatch) { return { onIncreaseClick: () => dispatch(increaseAction) } } // Action Creator const increaseAction = { type: 'increase' } ~~~ 然后,使用`connect`方法生成容器组件。 ~~~javascript const App = connect( mapStateToProps, mapDispatchToProps )(Counter) ~~~ 然后,定义这个组件的 Reducer。 ~~~javascript // Reducer function counter(state = { count: 0 }, action) { const count = state.count switch (action.type) { case 'increase': return { count: count + 1 } default: return state } } ~~~ 最后,生成`store`对象,并使用`Provider`在根组件外面包一层。 ~~~javascript import { loadState, saveState } from './localStorage'; const persistedState = loadState(); const store = createStore( todoApp, persistedState ); store.subscribe(throttle(() => { saveState({ todos: store.getState().todos, }) }, 1000)) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ~~~