实现简单的 react-redux
发布时间:2020-12-15 06:47:26 所属栏目:百科 来源:网络整理
导读:http://www.jianshu.com/p/26bb9a27c77a?utm_campaign=maleskineutm_content=noteutm_medium=pc_all_hotsutm_source=recommendation 原理就是把 redux 的 store,放在 react 的 context 里 React.js 的 context 动手实现 React-redux(一):初始化工程 动手
http://www.jianshu.com/p/26bb9a27c77a?utm_campaign=maleskine&utm_content=note&utm_medium=pc_all_hots&utm_source=recommendation
原理就是把 redux 的 store,放在 react 的 context 里
import React,{Component} from 'react'; import PropTypes from 'prop-types'; export const connect = (mapStateToProps,mapDispatchToProps) => (WrappedComponent) => { class Connect extends Component { static contextTypes = { store: PropTypes.object }; constructor() { super(); this.state = { allProps: {} } } componentWillMount() { const {store} = this.context; this._updateProps(); store.subscribe(() => { this._updateProps(); }) } _updateProps() { const {store} = this.context; let stateProps = mapStateToProps ? mapStateToProps(store.getState(),this.props) : {}; // 额外传入 props,让获取数据更加灵活方便 let dispatchProps = mapDispatchToProps ? mapDispatchToProps(store.dispatch,this.props) : {}; this.setState({ allProps: { // 整合普通的 props 和从 state 生成的 props ...stateProps,...dispatchProps,...this.props } }) } render() { return <WrappedComponent {...this.state.allProps}/>; } } return Connect; }; export class Provider extends Component { static propTypes = { store: PropTypes.object,children: PropTypes.any }; static childContextTypes = { store: PropTypes.object }; getChildContext() { return { store: this.props.store } } render() { return <div> {this.props.children} </div> } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- 如何使用xpath选择以下同级/ xml标记
- react构建淘票票webapp,及react与vue的简单比较
- vb.net – 重构Visual Studio 2005 for VB中的功
- iphone – Xcode在调试时失去与设备的连接
- 【第881期】Hybrid 开发:JsBridge - Web和客户端
- c# – .NET:为什么TryParseExact在Hmm和Hmmss上
- C#通过Socket快速判断数据库连接是否正常
- Swift Optionals: When to use if let, when ? a
- ruby-on-rails – Rails 3嵌套属性:如何将匹配记
- PostgreSQL创建只读用户
热点阅读