企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
API文档:http://cn.redux.js.org/docs/react-redux/ ## 一、简单示例 ![](https://box.kancloud.cn/5d1b354bbabbcc0fe963417f80a7748c_88x36.gif) ~~~ 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') ) ~~~ provider工作示意图 ![](https://box.kancloud.cn/bc6ab36774217855cd00f14cf0f56018_700x253.png) > provider就像是一个电路板,把各元件插上去之后就能够互相通信了,而不需要单独给元件之间另外拉线 二、简化合并 ~~~ 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 { constructor(props) { super(props); this.propTypes = { value: PropTypes.number.isRequired, onIncreaseClick: PropTypes.func.isRequired } } render() { const { value, onIncreaseClick } = this.props; return ( <div> <span>{value}</span> <button onClick={onIncreaseClick}>Increase</button> </div> ); } } // Connected Component const App = connect( function(state) { return {value: state.count}; }, function(dispatch) { return { onIncreaseClick: () => dispatch({ type: 'increase' }) }; } )(Counter); // Store const store = createStore((state={count: 0}, action) => { const count = state.count; switch (action.type) { case 'increase': return { count: count + 1 }; default: return state; } }); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ~~~ 参考链接:http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html https://www.jianshu.com/p/ef6269d9d75a