简体   繁体   English

在子组件React.js中添加路由

[英]Adding routes in child component React.js

I'm trying to add routes inside a child component but somehow it always returns 'NOT FOUND'. 我正在尝试在子组件内添加路由,但始终以某种方式返回“找不到”。 This is my code: 这是我的代码:

App.js: App.js:

class App extends Component {
  constructor(props){
    super(props);
    this.state = {};  
    this.handleLogout = this.handleLogout.bind(this); 
  }

  handleLogout(){
    sessionStorage.clear(); 
    window.location.replace('/login'); 
  }

  componentWillMount(){
      if(sessionStorage.getItem('access_token') != null && sessionStorage.getItem('id_token') != null){
          this.setState({loggedIn: true}); 
          console.log(sessionStorage.getItem('id_token')); 
      }
      else{
          this.setState({loggedIn: false}); 
      } 
  }
  render() {
    return (
        <BrowserRouter>
          <div>
            <title>Webshop</title> 
            <NavBar loggedIn={this.state.loggedIn} />
            <Switch>
                    {/*Routes need to be include in App.js otherwise root can't find the paths*/}
                    <Route exact path='/' component={Home}/>
                    <Route exact path='/categories' component={Categories}/>
                    <Route exact path='/login' component={Login}/>
                    <Route exact path='/register' component={Register}/>

                    {(this.state.loggedIn) ? 
                    <Route exact path='/logout' render={(props) => (<Logout logOutHandler={this.handleLogout} {...props}/>)} />                    
                    : null}

                    {(this.state.loggedIn) ? 
                    <Route exact path='/profile' component={Profile} />
                    : null }

                    <Route render={function(){
                        return (<NotFound/>); 
                    }}/>
                </Switch>
              <Footer/>
          </div>  
        </BrowserRouter>
    );
  }
}

Profile.js: Profile.js:

class Profile extends Component {
    constructor(props){
        super(props);
        this.id = jwt_decode(sessionStorage.getItem('id_token'))['id'];
        this.getUserData = this.getUserData.bind(this);
        this.getUserData(this.id);
        this.state = {}
        console.log(this.data);   
    } 

    getUserData(_id){
       var user = new User(); 
       var userPromise = user.user_data(_id);
       userPromise.then(
           (val) => { 
               this.setState({email: val.email,
                              firstName: val.firstName,
                              lastName: val.lastName});  
           }
       )        
    }
    render(){
        return(
            <div>
                <BrowserRouter>
                <Switch>
                    <Route exact path='/address' component={UserAddress}/>
                </Switch>
                </BrowserRouter>
                <Container className='content-container'>
                    <Row>
                        <Col md={4}>
                            <Card>
                                <CardBody>
                                    <Row>
                                        <Col md={12}>
                                            <Button className='float-right' color='secondary' size='sm'>
                                                <i className='fa fa-pencil'></i>
                                            </Button>
                                        </Col>
                                        <Col md={12}>
                                            <img className='profileImage'  alt='Profile' src={logo} width={150} height={150}/>
                                            <Table>
                                                <tbody>
                                                    <tr>
                                                        <th>Name</th>
                                                        <td>{this.state.firstName}</td>
                                                    </tr>
                                                    <tr>
                                                        <th>Surname</th>
                                                        <td>{this.state.lastName}</td>
                                                    </tr>
                                                    <tr>
                                                        <th>Email</th>
                                                        <td>{this.state.email}</td>
                                                    </tr>
                                                    <tr>
                                                        <th>Password</th>
                                                        <td>********</td>
                                                    </tr>
                                                </tbody>
                                            </Table>
                                        </Col>
                                    </Row>
                                </CardBody>
                            </Card>
                        </Col>
                        <Col md={8}>
                            <Card>
                                <CardBody>
                                    <Row>
                                        <Col md={12}>

                                            <Link to='/address'>
                                            <Button className='float-right' size='sm' color='success'>
                                                <i class="fa fa-plus">
                                                </i>
                                            </Button>
                                            </Link>
                                        </Col>
                                        [Here comes a foreach loop fetching all the UserAddress, visualizing them as one card per address, with an remove and edit button]
                                    </Row>
                                </CardBody>
                            </Card>
                        </Col>
                    </Row>
                </Container>
            </div>
        )
    }
}

I want to add a route inside Profile.js which redirects to my new component UserAddress but I can't get it to work. 我想在Profile.js中添加一条路由,该路由重定向到我的新组件UserAddress,但无法正常工作。 I have no errors only returning my 'NOT FOUND' message which is defined in App.js. 我没有错误,只返回了App.js中定义的“找不到”消息。 Could anyone help me out 谁能帮我

First, you need to remove the exact from your profile route. 首先,您需要从个人资料路由中删除exact信息。

<Route path='/profile' component={Profile} />

Your child route should start with '/profile', so React will render Profile.js and then UserAddress.js . 您的子路由应以'/ profile'开头,因此React将先渲染Profile.js然后再渲染UserAddress.js

<Route exact path='/profile/address' component={UserAddress}/>

And you dont need to define another BrowserRouter inside the Profile.js . 而且您不需要在Profile.js内定义另一个BrowserRouter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM