我正在开发一个基于 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/