反应Js,重构我的重定向方法

时间:2018-01-11 20:54:04

标签: javascript reactjs

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

componentWillReceiveProps({auth}) {
    if (auth) {
      this.props.history.push('/login') 
    }
  }

我已将此代码复制十次,有最好的方法吗?我想重构你有解决方案吗?

由于

1 个答案:

答案 0 :(得分:2)

对此等跨领域问题的建议是使用higher order components

HOC允许您包装现有组件,以便拦截props并应用更高阶逻辑(如身份验证或日志记录等),然后在HOC完成其工作时将支持传递给包装组件

一个粗略的例子可能是:

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

     componentWillReceiveProps({ auth }) {
        if (auth) {
           // redirect
        }
      }
      render() {
        return <WrappedComponent {...this.props} />;
      }
    };
  }

用法是:

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

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