【问题标题】:Conditional Routing and Conditional Rendering in ReactJS and React routerReactJS 和 React 路由器中的条件路由和条件渲染
【发布时间】:2018-01-22 22:40:03
【问题描述】:

我有一个问题,我尝试在网上查找,但找不到我需要的内容,但这可能是因为我无法正确表达我的问题。

我正在整理一个 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 与状态中的“用户”给出的用户 ID 匹配,我希望个人资料页面仅加载和呈现用户全名

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

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

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

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    另一种方法是将Profilecontainer 视为受保护的 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} />
    

    【讨论】:

      【解决方案2】:

      我会在渲染函数中做这样的事情

      let viewToRender

      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 }
      

      【讨论】:

        猜你喜欢
        • 2019-04-25
        • 2023-03-22
        • 2021-11-14
        • 2021-10-27
        • 2020-03-23
        • 2020-06-21
        • 2020-05-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多