[React] Use React Context to Manage Application State Through Routes
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了[React] Use React Context to Manage Application State Through Routes,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2369字,纯文字阅读大概需要4分钟。
内容图文
![[React] Use React Context to Manage Application State Through Routes](/upload/InfoBanner/zyjiaocheng/1157/cdfcf0f8bea14caeba09790ceed4d268.jpg)
We’ll create a Router component that will wrap our application and manage all URL related state. We’ll see how we can use React’s built in context mechanism to pass data and functions between components without having to pass props all the way down through the component tree.
// index.js ReactDOM.render( <MuiThemeProvider> <Router><App /></Router> </MuiThemeProvider>, document.getElementById(‘root‘));
On the top level, we add Router component to wrap our App component.
export class Router extends Component { state = { route: getCurrentPath() }; handleLinkClick = (route) => { this.setState({route}); history.pushState(null, ‘‘, route); }; staticchildContextTypes = { route: React.PropTypes.string, linkHandler: React.PropTypes.func }; getChildContext() { return { route: this.state.route, linkHandler: this.handleLinkClick }; } render() { return ( <div>{this.props.children}</div> ); } }
We need to pass the props to the children so that Link component can know current url state. To do this, we using ‘Context‘ instead of ‘passing the props down to children‘.
Becasue there are two problems with this. One, in a complex app, that could potentially mean passing the same item down many levels. This could mean a lot of maintenance if things need to change.
The second problem is that, in this setup, app is being placed inside the router through a call to this.props.children. We can‘t just add props onto the app component in our render function. The way we‘re going to handle this is through React‘s context mechanism.
import React, {Component} from‘react‘; const styles = { padding: ‘8px‘ }; export class Link extends Component { static contextTypes = { route: React.PropTypes.string, linkHandler: React.PropTypes.func }; render() { const activeClass = this.context.route === this.props.to ? ‘active‘: ‘‘; const handleClick = (ev) => { ev.preventDefault(); this.context.linkHandler(this.props.to); }; return ( <a href="#" style={styles} className={activeClass} onClick={handleClick}>{this.props.children}</a> ); } } Link.PropTypes = { to: React.PropTypes.string.isRequired };
Last, in the Link component, we can use the Context to access what we have defined for Router compoent.
原文:http://www.cnblogs.com/Answer1215/p/6362954.html
内容总结
以上是互联网集市为您收集整理的[React] Use React Context to Manage Application State Through Routes全部内容,希望文章能够帮你解决[React] Use React Context to Manage Application State Through Routes所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。