【问题标题】:porting a functional Component to Class based Component将功能组件移植到基于类的组件
【发布时间】:2019-03-17 03:17:59
【问题描述】:

我需要将此基于功能的 Component 转换为基于类的 Component 并创建一个 PrivateAuth Component 。 这是 PrivateAuth 功能组件。

function PrivateRoute({ component: Component, ...rest }) {
  return (
    <Route
      {...rest}
      render={props =>
        fakeAuth.isAuthenticated ? (
          <Component {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
}

这是我尝试过的基于类的组件。

class PrivateRoute extends React.Component{
    render(){
        console.log('this.props',this.props);
         const{ component: Component, ...rest } =this.props;
        return(
            <Route
            render={props =>
              fakeAuth.isAuthenticated ? (
                <Component {...props} />
              ) : (
                <Redirect
                  to={{
                    pathname: "/login",
                    state: { from: props.location }
                  }}
                />
              )
            }
          />
        );
    }
}

我得到了错误 超过最大更新深度。

【问题讨论】:

  • 你没有像在你的函数组件中那样在Route 上传播休息:{...rest}。否则它们看起来是一样的。您确定功能组件版本有效吗?
  • 有什么问题?我刚刚尝试了您提供的解决方案并且它有效。不要忘记将{...rest} 也分配给&lt;Route&gt;。这可能是您的任何组件中的问题,或者只是您声明路由器的方式。如果它来自另一个组件,您可以检查错误吗?

标签: javascript reactjs


【解决方案1】:
  // don't spread rest here
  const{ component: Component, rest } =this.props;

    <Route
        // and you can here spread rest like before
        {...rest}
        render={props =>
          fakeAuth.isAuthenticated ? (
          <Component {...props} />

【讨论】:

  • 我认为 OP 仍然希望 ...rest 将除 component 之外的所有内容分解为一个对象。
猜你喜欢
  • 1970-01-01
  • 2020-10-07
  • 2021-11-27
  • 1970-01-01
  • 2020-09-28
  • 2020-10-27
  • 2019-07-10
  • 1970-01-01
  • 2019-11-21
相关资源
最近更新 更多