[React] Use React Context to Manage Application State Through Routes

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);
    };

    static childContextTypes = {
        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.

 

posted @   Zhentiw  阅读(255)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示