javascript - React - 如果用户没有权限,如何不在子组件内部运行函数

标签 javascript reactjs

我正在开发一个基于 React 的应用程序,在使用 HasRole 组件渲染一些 jsx 之前,我正在检查用户的许可。一切正常,除非我有一个函数作为 HasRole 组件的子组件,如果用户也没有权限,则每次父组件呈现时都会调用该函数。我该如何防止这种情况发生。

HasRole.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

class HasRole extends Component {
  render() {
    const { children, role, requiredRole } = this.props;
    if(!requiredRole.includes(role)) return null;
      return children;
    }
  }

  const getMapStateToProps = (extendWith = {}) => state => {
    return {
      role: state.auth.userType,
        ...extendWith
      }
  }

export default connect(getMapStateToProps)(HasRole);

当我使用 HasRole 组件检查权限时,如果用户也没有权限,则执行 {this.renderUsers}

MovieShow.js

import React, { Component } from 'react';
import HasRole from '../has-role';

class MovieShow extends Component{
  constructor(props){
    super(props);
  }

  renderUsers(){
    ...
  }
  render(){
    return(

       ...
       <HasRole requireRole={["admin"]}>
           {this.renderUsers} // this will run if user is not admin also but the component wont be shown
       </HasRole>

  }
}

提前致谢!

最佳答案

将 rendersUsers 拖出类,使其成为无状态功能组件。

https://reactjs.org/docs/components-and-props.html

通过这样做,您应该能够将 requireRole 参数传递给它,并将其锁定在权限后面。

关于javascript - React - 如果用户没有权限,如何不在子组件内部运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49666271/

相关文章:

javascript - 防止 Javascript 用 NaN 替换字符串的开头?

javascript - React - 单击按钮后根据用户输入的文本更新类组件中的状态

javascript - 文本在输出中垂直上下跳动。使用 "document.getElementById("firstDiv").innerHTML = document.getElementById ("location").value;"

javascript - 从 jQuery 可拖动句柄中排除项目

javascript - createbottomtabnavigator 在所有屏幕上都不可见

reactjs - TS2339 : Property 'getBoundingClientRect' does not exist on type 'never'

javascript - 如何在 React Flux 架构中通过一个操作将数据传播到多个存储?

javascript - jQuery $.delegate() 单个选择器多个事件还是 $.bind() 更好的解决方案?

node.js - Bootstrap 突然不适用于我的 React JS 项目

javascript - 如何为 ReactJS 类创建基类