ReactJS和React路由器中的条件路由和条件渲染

时间:2018-01-22 22:40:04

标签: reactjs react-router

我有一个问题,我尝试在线查找但找不到我需要的东西,但这可能是因为我无法正确提出问题。

我有一个React项目我正在整理,我想为人们提供用户个人资料页面。这是我到目前为止所拥有的。

<Route path="/profile/:user" render={(routeProps) => (<Profile {...routeProps} {...this.state} /> )}/>

这是在我的index.js中,为不同的用户设置我的个人资料页面的路线,以下是我的个人资料页面的内容

import React from 'react';
import ReactDOM from 'react-dom';
import { NavLink } from 'react-router-dom';

export class Profile extends React.Component{
    constructor(props){
        super(props);
        this.state={
            user: this.props.user,
            fullname: this.props.fullname,
            picture: this.props.picture
        };
    }
    render(){
        return(
            <h1>{this.state.fullname}</h1>      
        );
    }
}

现在我的问题是这个。我希望配置文件页面只加载并呈现用户全名,如果URL匹配状态中'user'给出的userID

在我的index.js中我有硬编码的用户名和全名值来测试它,它们是这样设置的

constructor(props){
        super(props);
        this.state = {
            user:"AFC12345",
            fullname:"Bob Ross"
        };

我想在访问“http://localhost:8080/#/Profile/AFC12345”时只显示“个人资料”页面,目前它会为我发送的任何“个人资料/ xxxx”呈现个人资料页面。

2 个答案:

答案 0 :(得分:2)

另一种方法是将Profile容器视为受保护的URL,并使用与身份验证流相同的动态。

import React from 'react';
import { Redirect } from 'react-router-dom';

const ProtectedProfile = ({ component: Component, ...rest }) => (
  <Route {...rest} render={ props => (
     props.user === props.match.params.user ? (
      <Component {...props} /> ) : (
       <Redirect to={{ pathname: '/404' }} /> )
      )} />
 );

然后在你的App / index.js

 <ProtectedProfile path="/profile/:user" component={Profile} />

答案 1 :(得分:1)

我会在渲染功能中做这样的事情

if (this.state.user === this.props.match.params.user) { viewToRender = <p>{this.state.fullname}</p> }else{ viewToRender = <p>Ids don't match</p> } .... return (){ viewToRender }

{{1}}
相关问题