gpt4 book ai didi

reactjs - Flow React : Cannot create element because React. 组件 [1] 不是 React 组件

转载 作者:行者123 更新时间:2023-12-03 13:33:06 29 4
gpt4 key购买 nike

几周前我刚刚开始使用 Flow,从一周前开始我就遇到了 Flow 错误,我不知道如何修复。

代码如下:

// @flow

import React, { Component } from "react";
import { Redirect, Route } from "react-router-dom";
import CookieStorage from "./../services/CookieStorage";
import type { Component as ComponentType } from "react";

type Props = {
component: ComponentType<any, any>
}

class ProtectedRoute extends Component<Props> {
render() {
const isAuthenticated = this.isAuthenticated();
const {...props} = this.props;
const AuthorizedComponent = this.props.component;

return (
<Route
{...props}
render={props => (
isAuthenticated ?
<AuthorizedComponent {...props} /> :
<Redirect to="/"/>
)}
/>
);
}

isAuthenticated(): boolean {
const data = CookieStorage.get("foobar");

return data !== null;
}
}

export default ProtectedRoute;

在这里流程抛出此错误:

Error:(23, 8) Cannot create `AuthorizedComponent` element because `React.Component` [1] is not a React component.

我不知道我是否对身份验证示例正常时要呈现的组件执行了错误的导入类型或错误的类型声明。

我从一个我不记得在哪里的网站复制了这段代码,但他正在使用 const {component: Component} = this.props 使用这段代码。并将其渲染为 <Component {...props} />对我来说,这似乎有点模棱两可,这就是为什么我稍微改变了声明,以便在阅读时更容易理解,但即使仍然执行与我复制此代码的片段完全相同的代码,流程仍然会抛出该错误。

我做了一个gist如果有人知道这个问题的解决方案并想要做出改变,如果没有人能够帮助我在这里解决这个问题,那么我将使用这个要点向他们的项目发送一个票证问题

最佳答案

尝试改用React.ComponentType

import type { ComponentType } from "react";

import React, { Component } from "react";
import { Redirect, Route } from "react-router-dom";
import CookieStorage from "./../services/CookieStorage";

type Props = {
component: ComponentType<any>
}

class ProtectedRoute extends Component<Props> {
render() {
const isAuthenticated = this.isAuthenticated();
const { component: AuthorizedComponent, ...props } = this.props;

return (
<Route
{...props}
render={props => (
isAuthenticated ?
<AuthorizedComponent {...props} /> :
<Redirect to="/"/>
)}
/>
);
}

isAuthenticated(): boolean {
const data = CookieStorage.get("foobar");
return data !== null;
}
}

export default ProtectedRoute;

参见https://flow.org/en/docs/react/types/#toc-react-componenttype

关于reactjs - Flow React : Cannot create element because React. 组件 [1] 不是 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55105801/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com