【问题标题】:Filter links in React Props在 React Props 中过滤链接
【发布时间】:2021-05-10 23:17:01
【问题描述】:

我有一个由表格组成的反应类组件。该表有一个编辑和删除按钮,如果用户未登录,我想禁用该按钮。我有一个 isAuthenticated 值,用于检查用户是否未登录,但不确定如何使用该变量如果用户未登录,则有条件地禁用或不呈现编辑和删除按钮。

【问题讨论】:

    标签: reactjs components state auth0 react-props


    【解决方案1】:

    你可以像这样传递isAuthenticated

    render() {
      const { isAuthenticated } = this.props.auth0;
      //....
      { this.exerciseList(isAuthenticated) }
    } 
    
    exerciseList(isAuthenticated) {
            return this.state.exercises.map(currentexercise => {
              return <Exercise exercise={currentexercise} deleteExercise={this.deleteExercise} key={currentexercise._id} isAuthenticated={isAuthenticated}/>;
            })
    }
    

    请注意,在exerciseList 中,它会传递给您的练习。然后,您可以引用props.isAuthenticated 并根据值有条件地渲染(如果isAuthenticatedfalse,我使用三元表达式返回null):

    const Exercise = props => (
    
        <tr>
          <td>{props.exercise.username}</td>
          <td>{props.exercise.description}</td>
          <td>{props.exercise.duration}</td>
          <td>{props.exercise.date.substring(0,10)}</td>
          { props.isAuthenticated ?
            <td><Link to={"/edit/"+props.exercise._id}>edit</Link> | <a href="/#" onClick={() => { props.deleteExercise(props.exercise._id) }}>delete</a></td>
          : 
          <td></td>
          }
        </tr>
      )
    

    【讨论】:

    • 太棒了,我会尝试一下,会及时更新!
    • 我只是稍微修改了一下,如果三元为假,则使用空的td
    • 一切正常,非常感谢!我的一个问题是表头,我应该使用三元表达式来隐藏它吗?还是说这不是有效的操作方式?
    • 很高兴它对你有用。我看到你是新来的,所以请考虑支持/接受答案。您可以随心所欲地使用三元 - 使用它不会影响“效率” - 它只是内联 if/else 的简写
    • 绝对可以,最后一个问题,如果我想访问 componentDidMount 函数中的 isAuthenticated 值,我该怎么做?如果经过身份验证,我基本上只想获得与特定用户相关的练习,否则如果未经身份验证,其他用户的新闻源练习
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2021-07-19
    • 2019-08-08
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多