我正在尝试与一个团队一起构建一个React应用程序,并试图找出创建一个“高阶” React组件(一个包装另一个组件)以与Redux数据存储结合执行身份验证的最佳方法。
到目前为止,我的方法是创建一个模块,该模块由一个函数组成,该函数根据是否有经过身份验证的用户来返回新的React组件。
export default function auth(Component) {
class Authenticated extends React.Component {
// conditional logic
render(){
const isAuth = this.props.isAuthenticated;
return (
<div>
{isAuth ? <Component {...this.props} /> : null}
</div>
)
}
}
...
return connect(mapStateToProps)(Authenticated);
}
这使我团队中的其他人可以轻松地指定某个组件是否需要某些权限。
render() {
return auth(<MyComponent />);
}
如果您要执行基于角色的检查,则这种方法很有意义,因为您可能只有几个角色。在这种情况下,您可以致电auth(<MyComponent />, admin)
。
对于基于权限的检查,传递参数变得笨拙。但是,在构建组件时(以及在团队环境中可管理)在组件级别指定权限可能是可行的。设置静态方法/属性似乎是一个不错的解决方案,但据我所知,es6类导出为函数,但不会显示可调用方法。
有没有办法访问导出的React组件的属性/方法,以便可以从包含的组件中访问它们?
onEnter很棒,在某些情况下很有用。但是,以下是onEnter无法解决的一些常见身份验证和授权问题:
如果商店更新(但不是当前路由),请重新检查身份验证/授权
如果子路由在受保护的路由下更改,请重新检查身份验证/授权
另一种方法是使用高阶组件。
您可以使用 Redux-auth-wrapper提供的高阶组件,以便于组件读取和应用身份验证和授权约束。
要获取子方法,可以使用:refs, callback and callback from refs
要获得儿童道具,您可以使用:this.refs.child.props.some or compInstance.props.some
方法和道具示例:
class Parent extends Component {
constructor(props){
super(props);
this.checkChildMethod=this.checkChildMethod.bind(this);
this.checkChildMethod2=this.checkChildMethod2.bind(this);
this.checkChildMethod3=this.checkChildMethod3.bind(this);
}
checkChildMethod(){
this.refs.child.someMethod();
console.log(this.refs.child.props.test);
}
checkChildMethod2(){
this._child2.someMethod();
console.log(this._child2.props.test);
}
checkChildMethod3(){
this._child3.someMethod();
console.log(this._child3.props.test);
}
render(){
return (
<div>
Parent
<Child ref="child" test={"prop of child"}/>
<ChildTwo ref={c=>this._child2=c} test={"prop of child2"}/>
<ChildThree returnComp={c=>this._child3=c} test={"prop of child3"}/>
<input type="button" value="Check method of child" onClick={this.checkChildMethod}/>
<input type="button" value="Check method of childTwo" onClick={this.checkChildMethod2}/>
<input type="button" value="Check method of childThree" onClick={this.checkChildMethod3}/>
</div>
);
}
}
class Child extends Component {
someMethod(){
console.log('someMethod Child');
}
render(){
return (<div>Child</div>);
}
}
class ChildTwo extends Component {
someMethod(){
console.log('someMethod from ChildTwo');
}
render(){
return (<div>Child</div>);
}
}
class ChildThree extends Component {
componentDidMount(){
this.props.returnComp(this);
}
someMethod(){
console.log('someMethod from ChildThree');
}
render(){
return (<div>Child</div>);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句