Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React Js,重构我的重定向方法_Javascript_Reactjs - Fatal编程技术网

Javascript React Js,重构我的重定向方法

Javascript React Js,重构我的重定向方法,javascript,reactjs,Javascript,Reactjs,我有多个组件,我在其中检查用户是否有权在登录页面上重定向 componentWillReceiveProps({auth}) { if (auth) { this.props.history.push('/login') } } 我已经把这个代码复制了十次,有没有最好的方法?我想重构你有解决方案吗 谢谢对于此类交叉关注点的建议是使用 HOC允许您包装现有组件,这样您就可以拦截props,并应用更高阶的逻辑,如身份验证或日志记录等,然后在HOC完成工作后将这些p

我有多个组件,我在其中检查用户是否有权在登录页面上重定向

componentWillReceiveProps({auth}) {
    if (auth) {
      this.props.history.push('/login') 
    }
  }
我已经把这个代码复制了十次,有没有最好的方法?我想重构你有解决方案吗


谢谢

对于此类交叉关注点的建议是使用

HOC允许您包装现有组件,这样您就可以拦截
props
,并应用更高阶的逻辑,如身份验证或日志记录等,然后在HOC完成工作后将这些props传递给包装的组件

一个粗略的例子可以是:

function withAuth(WrappedComponent) {
    return class extends React.Component {

     componentWillReceiveProps({ auth }) {
        if (auth) {
           // redirect
        }
      }
      render() {
        return <WrappedComponent {...this.props} />;
      }
    };
  }
带auth的函数(WrappedComponent){
返回类扩展了React.Component{
componentWillReceiveProps({auth}){
if(auth){
//重定向
}
}
render(){
返回;
}
};
}
用途如下:

const Hoc = withAuth(MyExistingComponent);
...
render() {
    return <Hoc {...props} />
}
const Hoc=withAuth(MyExistingComponent);
...
render(){
返回
}

基类是另一种选择,但很快就会失去焦点,成为通用共享逻辑的转储。我认为HOC更干净。

对于这样的交叉关注点,建议使用

HOC允许您包装现有组件,这样您就可以拦截
props
,并应用更高阶的逻辑,如身份验证或日志记录等,然后在HOC完成工作后将这些props传递给包装的组件

一个粗略的例子可以是:

function withAuth(WrappedComponent) {
    return class extends React.Component {

     componentWillReceiveProps({ auth }) {
        if (auth) {
           // redirect
        }
      }
      render() {
        return <WrappedComponent {...this.props} />;
      }
    };
  }
带auth的函数(WrappedComponent){
返回类扩展了React.Component{
componentWillReceiveProps({auth}){
if(auth){
//重定向
}
}
render(){
返回;
}
};
}
用途如下:

const Hoc = withAuth(MyExistingComponent);
...
render() {
    return <Hoc {...props} />
}
const Hoc=withAuth(MyExistingComponent);
...
render(){
返回
}

基类是另一种选择,但很快就会失去焦点,成为通用共享逻辑的转储。我认为HOC更干净。

取决于应用程序的布局。“多个组件”是否有共同的父级或父级?如果是这样,只需让该组件检查auth。用户通过身份验证后,您应该只渲染依赖于auth的组件。具体取决于应用程序的布局。“多个组件”是否有共同的父级或父级?如果是这样,只需让该组件检查auth。在用户经过身份验证后,应该只渲染依赖于auth的组件。嘿,dashton,我认为最好这样做:使用auth导出默认值(MyExistingComponent)?嘿,dashton,我认为最好这样做:用auth导出默认值(MyExistingComponent)?