react 路由 react-router-dom

import React from 'react';
import DataList from './data'
import Tr from './Tr'
// import One from '../One'
import User from '../User'
import Two from '../Two'
import NotFound from '../NotFound';
import {Redirect,NavLink,Route,Switch} from 'react-router-dom';
//Redirect 重定向标签 NavLink路由跳转标签 Route显示路由的窗口 Switch用来保证路由窗口只显示一个路由标签 用来包裹Route标签 class Tab extends React.Component{ render(){
return ( <div> { <div>
          //路由书写的规则 exact是用来精确匹配 component={组件名} <NavLink to='/two/companies'>two</NavLink> <NavLink to='/one/users'>one</NavLink> <Switch> <Redirect exact from='/' to='/one/companies' /> <Route path='/one/:type?' component={User}/> <Route path='/two/:id?' component={Two}/> <Route component={NotFound}></Route> </Switch> </div> }</div> ) } } export default Tab;

子路由:

import React from 'react';
import axios from 'axios';
import OneTwo from './OneTwo'
import {Switch,NavLink,Route} from 'react-router-dom';
import NotFound from './NotFound'
class User extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            list : []
        }
    };
    componentDidMount(){ //组件挂载以后函数 通过this.props.match.params获取路由传参的值。
        let {type} = this.props.match.params;
        this.getData(type);
    };
    getData(id){
        axios.get('http://localhost:4000/'+id)
        .then((res)=>{
            this.setState({
                list:res.data
            })
        })
    };
    componentWillReceiveProps(){ //组件将更新props的值
        let {type} = this.props.match.params;
        this.getData(type);
    }
    render(){
        let {list} = this.state;
        return (
            <div>
                {list.map((item)=>{
                    return (
                        <div key={item.id}>
                  //路由字符串的写法拼接写法 对象写法在下面 <NavLink to={this.props.match.url+'/'+item.id}>{item.name}</NavLink> </div> ) })} <Switch>
            //组件该显示的位置要放出循环外 <Route path="/one/users/:userid" component={OneTwo}/> </Switch> </div> ) } } export default User;

 

详情组件:

import React from 'react';
import axios from 'axios';
class OneTwo extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            list : {}
        }
    }
    getData(id){
    //将路由传来的id进行匹配拿到数据 axios.get(
'http://localhost:4000/users/'+id) .then((res)=>{ this.setState({ list: res.data }) }) } componentDidMount(){ let {userid} = this.props.match.params; this.getData(userid); }; componentWillReceiveProps(){ let {userid} = this.props.match.params; this.getData(userid); } render(){ let {list} = this.state; return ( <div>
          //枚举对象返回一个key值数组 {Object.keys(list).map((item)=>{ return ( <div key={item}> {item}:{list[item]} </div> ) })} </div> ) } } export default OneTwo;

感觉就和vue一样

posted @ 2018-08-13 21:03  悔创阿里-杰克马  阅读(807)  评论(0编辑  收藏  举报
求投食~(点图即可)