React中的“虫洞”——Context
当我们写React时,我们总是通过改变State和传递Prop对view进行控制,有时,也会遇到一点小麻烦。 背景但是随着我们的应用变的越来越复杂,组件嵌套也变的越来越深,有时甚至要从最外层将一个数据一直传递到最里层(比如当前user的信息)。 理论上,通过prop一层层传递下去当然是没问题的。不过这也太麻烦啦,要是能在最外层和最里层之间开一个穿越空间的虫洞就好了。 幸运的是,React的开发者也意识到这个问题,为我们开发出了这个空间穿越通道 —— Context。 使用看起来很高大上的Context使用起来却异常简单。 基本使用假设我们有下面这样的组件结构。
D组件需要获取在A组件中用户信息应该怎么办?有了Context,我们可以这么做。 // Component A class A extends React.Component { // add the following method getChildContext() { return { user: this.props.user } } render() { <div>{this.props.children}</div> } } // add the following property A.childContextTypes = { user: React.PropTypes.object.isRequired } // Component D class D extends React.Component { render() { <div>{this.context.user.name}</div> } } // add the following property D.contextTypes = { user: React.PropTypes.object.isRequired } 很简单吧,只要在外层定义一个 在lifecycle方法中使用根据官方的文档,Context在以下的lifecycle方法中也是可以使用的 void componentWillReceiveProps( object nextProps,object nextContext ) boolean shouldComponentUpdate( object nextProps,object nextState,object nextContext ) void componentWillUpdate( object nextProps,object nextContext ) void componentDidUpdate( object prevProps,object prevState,object prevContext ) stateless组件中使用同时,在最新的stateless组件中,也是可以使用Context的,而且更加简单。 function D(props,context) { return ( <div>{this.context.user.name}</div> ); } D.contextTypes = { user: React.PropTypes.object.isRequired } 使用场景既然Context使用起来如此方便,是不是就应该多多用它呢? 比如:
所以,当发现使用Context仅仅为了少打几个字而不考虑存放何种数据,那很可能用错Context了…… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- ruby-on-rails – 403使用s3cmd工具上传到Amazon S3的Paper
- c – Xamarin iOS Native连接在模拟器上工作,在设备上重复符
- c# – 如何在WPF中懒洋洋地创建UI元素?
- c – 可以通过模板间接访问基类中的私有类型
- ruby-on-rails – Rails和Memcached:优化多个提取
- Ruby gem用于使用xsd:import使用Webservices wsdl
- c# – 货币库
- cocos2d 之autorelease\ratain\release的理解
- 创建一个下载自己的依赖关系的Java应用程序
- cocos 3.2 ListView渲染bug解决办法