Home >Web Front-end >JS Tutorial >Learn react-router-dom through a user management example

Learn react-router-dom through a user management example

一个新手
一个新手Original
2017-10-12 09:34:491562browse

We learn react-router-dom through a user management example

This example includes 9 small components

App.js introduces components

Home.js home page component

User.js user management component

- UserList.js User list component

- UserAdd.js User add component

- UserDetail.js User details component

Profile.js Personal center component

Login.js User login component

Protected.js handles login Component (we simulate login)

We first create an App component as a component introduced in our project

import React, {Component} from 'react';//Router 容器,它是用来包裹路由规则的//Route 是路由规则//BrowserRouter基于h5的。兼容性不好//引入react-router-demoimport {HashRouter as Router, Route,Link,NavLink,Switch} from 'react-router-dom';//引入我们需要的组件import Home from "./Home";
import User from "./User";
import Profile from "./Profile";
import Login from "./Login";
import Protected from './Protected'//定义一个App组件export default class App extends Component {
    render() {        //定义一个我们选中的状态
        let activeStyle={color:&#39;red&#39;}        return (            <Router>
                <p className="container">
                    <nav className=&#39;nav navbar-default&#39;>
                        <p className="container-fluid">
                            <a className="navbar-brand">用户管理</a>
                        </p>
                        <ul className="nav">
                            <li className=&#39;navbar-nav&#39;><NavLink exact activeStyle={activeStyle} to="/">首页</NavLink></li>
                            <li className=&#39;navbar-nav&#39;><NavLink activeStyle={activeStyle} to="/user">用户管理</NavLink></li>
                            <li className=&#39;navbar-nav&#39;><NavLink activeStyle={activeStyle} to="/profile">个人中心</NavLink></li>
                        </ul>
                    </nav>
                    <p>
                        {/*Switch是匹配*/}
                        {/*exact 我们匹配/斜杠时候,就匹配第一个*/}                        <Switch>
                        <Route exact path="/" component={Home}/>
                        <Route path="/user" component={User}/>
                            <Protected path="/profile" component={Profile}/>
                            <Route path="/login" component={Login}/>

                        </Switch>
                    </p>
                </p>
            </Router>        )
    }
}

The App component allows us Introduced components, in this component, we need to pay attention to the outermost Router

This is the routing container, our routing rule Route needs to be wrapped in the date

Route contains two attributes, path and component

path points to the routing path, and component points to the component to be jumped

Our route navigation is usually Link and NavLink

These two functions have the same function, both are route jumps, but NavLink has an attribute used to display the jump selected style, the activeStyle attribute, which is written to display the highlighted style, and receives an object {}

## in Our route navigation has a to attribute

the to attribute is the path to jump to in our route

The following is the User.js component, which mainly includes two routes, NavLink and Route. It has the same meaning as above, switching the two components NavLink and Route

import React, {Component} from &#39;react&#39;import {Link,Route,NavLink} from &#39;react-router-dom&#39;import UsersList from &#39;./UsersList&#39;import UsersAdd from &#39;./UsersAdd&#39;import UserDetail from "./UserDetail";
export default class User extends Component {
    render() {
        let activeStyle={color:&#39;red&#39;}        return (            <p className=&#39;row&#39;>
                <p className="col-sm-3">
                    <nav>
                        <ul className="nav nav-stacked">
                            <li><NavLink activeStyle={activeStyle} to="/user/list">用户列表</NavLink></li>
                            <li><NavLink activeStyle={activeStyle} to="/user/add">添加用户</NavLink></li>
                        </ul>
                    </nav>
                </p>
                <p className="col-sm-9">
                    <Route path="/user/list" component={UsersList}></Route>
                    <Route path="/user/add" component={UsersAdd}></Route>
                    <Route path="/user/detail/:id" component={UserDetail}></Route>
                </p>
            </p>        )
    }
}

- UserAdd.js User Add Component

import React, {Component} from &#39;react&#39;export default class UsersAdd extends Component {
    handleSubmit=()=>{
        let username=this.refs.username.value;
        let password=this.refs.password.value;
        let user={username,password,id:Date.now()};
        let users=JSON.parse(localStorage.getItem(&#39;USERS&#39;)||"[]");
        users.push(user);
        localStorage.setItem(&#39;USERS&#39;,JSON.stringify(users));        this.props.history.push(&#39;/user/list&#39;)
    }
    render() {        /*
        * history 用来跳转页面
        * location.pathname 用来存放当前路径
        * match代表匹配的结果
        *
        * */
        return (            <form onSubmit={this.handleSubmit}>
                <p className="form-group">
                    <label htmlFor="username" className="control-label">
                        用户名                    </label>
                    <input type="text" className="form-control" ref="username" placeholder="用户名"/>
                </p>
                <p className="form-group">
                    <label htmlFor="username" className="control-label">
                        密码                    </label>
                    <input type="password" className="form-control" ref="password" placeholder="密码"/>
                </p>
                <p className="form-group">

                    <input type="submit" className="btn btn-danger" />
                </p>
            </form>        )
    }
}

We cache the data added by the user on the page to facilitate the rendering of our user list page

<span style="font-size: 14pt;">localStorage.setItem(&#39;USERS&#39;,JSON.stringify(users));</span><br/><span style="font-size: 14pt;">缓存完成后跳转到列表详情页面userList</span><br/><span style="font-size: 14pt;">this.props.history.push(&#39;/user/list&#39;)</span>

- UserList.js User List Component

import React, {Component} from &#39;react&#39;import {Link} from &#39;react-router-dom&#39;export default class UsersList extends Component {
    constructor(){
        super();        
        this.state={users:[]}
    }
    componentWillMount(){
        let users = JSON.parse(localStorage.getItem(&#39;USERS&#39;) || "[]");        
        this.setState({users});
    }
    render(){        
    return (           
    <ul className="list-group">
               {                   
                       this.state.users.map((user,index)=>(                       
                       <li key={index} className="list-group-item">
                           <span>用户名:</span>
                           <Link to={`/user/detail/${user.id}`}>{user.username}</Link>
                          <span className="btn btn-danger" onClick={()=>{
                              let users=this.state.users.filter(item=>item.id!=user.id)                              this.setState({users});
                          }}>删除</span>
                       </li>                   ))
               }           </ul>        )
    }
}

componentWillMount() is the component cycle function after the component is mounted

In this hook In the function, we go to the USERS data stored in userAdd, and then render it to the page
9652a14b13a604fe13d387155c935dda{user. username}06f735b502bd5273dad825215f7c405b

Here we jump to the personal information details and bring everyone’s user ID

Then our user details page UserDetail.js component

import React, {Component} from &#39;react&#39;export default class UserDetail extends Component {
    render() {        // let user=this.props.location.state.user
        let users = JSON.parse(localStorage.getItem(&#39;USERS&#39;)||"[]");
        let id = this.props.match.params.id;
        let user = users.find(item=>item.id == id);        
        return (            
        <table className="table table-bordered">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>用户名</th>
                    <th>密码</th>
                </tr>
                </thead>
                <tbody>
                    <tr>
                    <td>{user.id}</td>
                    <td>{user.username}</td>
                    <td>{user.password}</td>
                    </tr>
                </tbody>
            </table>        )
    }
}

let id = this.props.match.params.id;

let user = users.find(item=>item.id == id);

Get the id brought by the route through match

Then determine the item with the same ID in users

and then render it to the page

. Then we determine the login. If there is no login, then Log in. You can view user management only after logging in.

import React from &#39;react&#39;;
import {Route, Redirect} from &#39;react-router-dom&#39;;//函数组件//把属性对象中的Component属性取出来赋给comp,把其它属性取出来赋给other对象//再把other对象的全部属性取出来赋给Route// component=组件// render函数 当路由匹配的时候,渲染的是render方法的返回值export default function ({component: _comp, ...rest}) {    return <Route {...rest} render={
        props => localStorage.getItem(&#39;login&#39;) ? <_comp/> :
            <Redirect to={{pathname: &#39;/login&#39;, state: {from: props.location.pathname}}}/>
    }/>    return null;
}

If you are not logged in, we will enter the login component. In fact, when we simulate login, we set a cache login to true and simulate permissions. In a real project, we Restricted through the background interface, route jump

import React, {Component} from &#39;react&#39;;
export default class Login extends Component {
    handleClick = ()=>{
        localStorage.setItem(&#39;login&#39;,&#39;true&#39;);
        console.log(this.props);        
        this.props.history.push(this.props.location.state.from);
    }
    render() {        
    return (            
    <p>
                   <button
                    onClick={this.handleClick}
                    className="btn btn-primary">登录                
                    </button>
            </p>        
            )
    }
}

Behind, our homepage Hone and Profile components are basically used to display personal information, that is, rendering, so I don’t need to write it!

Overall completed, routing is nested, and then different routing information is distinguished through routing parameters

The above is the detailed content of Learn react-router-dom through a user management example. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn