根据动态路线渲染反应组件

时间:2019-07-17 13:44:06

标签: reactjs react-router

我正在努力根据来自React-Router的路由来渲染组件。当路线是动态的时,我似乎无法找出匹配路线的方法。

我创建了一个组件“ Navbar”,我只想在特定路线上进行渲染。为此,我创建了一个单独的组件“ Tracker”,该组件与路线匹配并呈现“ Navbar”组件。

Tracker.js代码段:

class Tracker extends Component {
  render() {
var NavVisible =
      this.props.location.pathname === "/feed" ||
      this.props.location.pathname === "/explore" ||
      this.props.location.pathname === "/chatroom" ||
      this.props.location.pathname === "/username" ? (
        <Navbar />
      ) : null;
    return <div>{NavVisible}</div>;
  }
}

假设我必须在“ feed /(some_dynamic_path)”中显示导航栏组件,该怎么写条件?

一个解决方案将不胜感激。

谢谢。

编辑:App.js

import React, {Component} from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';


class App extends Component{


  render(){

  const DefaultContainer = () => (
    <div>

      <Route path='/home' component={ft}/>
        <Route path='/explore' component={exp}/>
        <Route path='/compose' component={add}/>
        <Route path='/chatroom' component={msg}/>
        <Route path='/user' component={usrpro}/>

        </div>
  )

return (
    <BrowserRouter>    
    <div className="App">
      <Tracker/>
      <Switch>
      <Route path='/' exact component={Splash}/>
      <Route exact path="/(compose)" component={noNavContainer}/>
      <Route exact path="/(newtext)" component={noNavContainer}/>
      <Route path="/(login)" component={login}/>
      <Route component={DefaultContainer}/>        
      </Switch>      
    </div>
    </BrowserRouter>
  );
}
}


export default App;

2 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

this.props.location.pathname === '/feed/' + this.props.params.id

可能会帮助您入门:https://jaketrent.com/post/access-route-params-react-router-v4/

答案 1 :(得分:0)

您可以在您的应用中包含各种网址的路由器。

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

class App extends React.Component {
  render () {
    return (
      <Router>
        <Home>
          <Switch>
            <Route path='/feed/:path_variable' component={Navbar} />
          </Switch>
        </Home>
      </Router>
    )
  }
}

还可以在导航栏组件中访问this.props.match.params.path_variable,其值会根据URL进行更改。

在这篇写得很好的文章中阅读有关它的更多信息。 https://scotch.io/courses/using-react-router-4/route-params