Как я могу уменьшить количество маршрутов в React js при разработке панели мониторинга? - PullRequest
0 голосов
/ 28 апреля 2020

Я разрабатываю панель мониторинга для одного из моих портфельных приложений, но из-за другой категории и разных операций CRUD число маршрутов увеличивается, а код выглядит большим. Можете ли вы предложить, как я могу управлять различными маршрутами панели мониторинга. Когда я щелкаю на Skill, то создаю маршрут (http://localhost: 3000 / Dashboard / Skill ), теперь в категории Skill, когда я нажимаю на представление Edit, затем снова создаются другие маршруты (http://localhost: 3000 / Dashboard / Skill / edit ) Аналогичным образом создается больше маршрутов для разных категорий. Как можно решить эту проблему.

// Панель инструментов. js

import React, { Component } from 'react'
import '../Css/Dashboard.css'
import Menu from './Dashboard/Menu'
import About from './Dashboard/About'
import Skill from './Dashboard/Skill'
import Experience from './Dashboard/Experience'
import Header from './Dashboard/Header'
import ExperienceView from '../Components/DashboardCrud/ExperienceView'
import { BrowserRouter,Route,Switch,Redirect} from "react-router-dom";
import {Link} from 'react-router-dom'

export class Dashboard extends Component {

  constructor(props) {
      super(props)

      this.state = {
           redirect:false
      }

      this.logout=this.logout.bind(this);
  }

  logout()
  {
    localStorage.setItem('token','');
    localStorage.clear();
    this.setState({
        redirect:true
    })
  }
 componentWillMount()
 {
     if(localStorage.getItem('token'))
     {
         console.log("Login successs")
     }
     else{
         this.setState({
             redirect:true
         })
     }
 }

    render() {

         if(this.state.redirect)
         {
             return (<Redirect to={'/Login'}/>)
         }

        const {match}=this.props;
        return (
            <div>
                <div>
               <Header></Header>
               <div class="sidebar">
               <Link to={`${match.url}`} >Menu</Link>
               <Link to={`${match.url}/About`} >About</Link>
               <Link to={`${match.url}/Skill`} >Skill</Link>
               <Link to={`${match.url}/Experience`} >Experience</Link>
               <a onClick={this.logout} ><span class="glyphicon glyphicon-log-out"></span>Log Out</a>

               </div>


           <div class="content">

                   <Switch> 

                   <Route path={`${match.url}/Skill/edit`} component={SkillEditView}></Route>
                   <Route path={`${match.url}/Skill/delete`} component={SkillDeleteView}></Route>

                   <Route path={`${match.url}` }  exact component={Menu}></Route>
                   <Route path={`${match.url}/About`} component={About}></Route>
                   <Route path={`${match.url}/Skill`} component={Skill}></Route>
                   <Route path={`${match.url}/Experience`} component={Experience}></Route>
                   </Switch> 
            </div>


           </div>
            </div>
        )
    }
}


export default Dashboard

// Умение. js

import React, { Component } from 'react'
import '../../Css/Dashboard/Menu.css'
import { getDashboard } from '../../Services/getDashboard'
import Load from '../../Components/Dashboard/Load'

export class Skill extends Component {

    constructor(props) {
        super(props)

        this.state = {
            Skills: [],
            isloading:true

        }
    }

    componentDidMount() {

        const response = getDashboard('skill');
        response.then((sucess) => {
            this.setState({
                Skills: sucess.data,
                isloading:false
            })
            console.log(this.Abouts)
        }).catch(er => {
            console.log(er)
        })

    }

    render() {

        if(this.state.isloading)
        {
            return(
              <div className="Loader_div">
                 <Load></Load>
              </div>  
            )
        }

        return (
            <div>
                <div class="container dashboard">
                    <h2 style={{ color: "red" }}>Skills Details </h2>
                    <p className="Menu_dash_desc">Edit the Skills Easily</p>
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>SkillName</th>
                                <th>value</th>
                                <th>Edit</th>
                                <th>Delete</th>


                            </tr>
                        </thead>
                        <tbody>
                            {
                                this.state.Skills.map((skill) => <tr>
                                    <td>{skill.SkillName}</td>
                                    <td>{skill.value}</td>

                                    <td>


                            <Link style={{ backgroundColor: "green", border: "none" }} class="btn btn-info btn-lg" to={`${match.url}/edit/`} ><span class="glyphicon glyphicon-pencil"></span></Link>

                                    </td>
                                    <td>


                            <Link style={{ backgroundColor: "green", border: "none" }} class="btn btn-info btn-lg" to={`${match.url}/delete/`} ><span class="glyphicon glyphicon-pencil"></span></Link>

                                    </td>

                                </tr>


                                )
                            }

                        </tbody>
                    </table>
                </div>

            </div>
        )
    }
}

export default Skill

dashboard Screen

1 Ответ

0 голосов
/ 28 апреля 2020

Вы не можете избежать этой ситуации. Для каждого маршрута («Навыки», «Опыт» и т. Д. c) вам необходимо иметь соответствующую массу маршрутов. И, может быть, если компоненты маршрутизации имеют одинаковую структуру, лучше будет создать общий шаблон и использовать композицию.

...