React Typescript:属性'path'在'IntrinsicAttributes&Pick <any,never>'类型上不存在

时间:2020-10-04 20:21:32

标签: reactjs typescript react-router

现在,受保护的路由配置几乎没有问题。 我正在使用react-router 5,已安装类型等。

错误: 键入'{path:string; component:()=>元素; }”不能分配给“ IntrinsicAttributes&Pick ”类型。 属性“ path”在类型“ IntrinsicAttributes&Pick ”上不存在。ts(2322)

App.tsx组件:

function App(props: any) {
    const { i18n } = useTranslation();
    useEffect(() => {
        if(localStorage.getItem('Locale')) {
            i18n.changeLanguage(localStorage.getItem('Locale') as string)
        }
    }, [])

    return (
        <Suspense fallback={<div>Loading...</div>}>
            <BrowserRouter>
                <Switch>
                    <Route exact path="/" component={Login} />
                    <Route exact path="/login" >
                        <Redirect to="/" />
                    </Route>
                    <ProtectedRoute path='/admin' component={AdminLayout} />
                </Switch>
            </BrowserRouter>
        </Suspense>
    );
}

export default App;

受保护的路线组件:

import React from 'react'
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom'
import { logoutUser } from './_Actions/UserActions';
import { Dispatch } from "redux";

class ProtectedRoute extends React.Component<any, any> {

    render() {
        var Component = this.props.component;
        console.log(this.state);
        
        const isAuthenticated = true;
       
        return isAuthenticated ? (
            <Component />
        ) : (
            <Redirect to={{ pathname: '/login' }} />
        );
    }
}

const mapStateToProps = (state: any) => ({
    ...state,
});
const mapDispatchToProps = (dispatch: Dispatch) => ({
    logOut: () => dispatch(logoutUser()),
});

export default connect(mapStateToProps, mapDispatchToProps)(ProtectedRoute);

将受保护的路由组件连接到Redux时遇到此错误。错误出现在App.tsx内部。

1 个答案:

答案 0 :(得分:1)

您的问题在于类型声明

class ProtectedRoute extends React.Component<any, any> {

connect HOC换行时,类型变为

ConnectedComponent<typeof ProtectedRoute, Pick<any, never>>

这就是错误中Pick<any, never>的起源。

通过使用React.Component<any, any>,您可以断言ProtectedRoute可以带道具。因此,当您传递带有特定键pathcomponent的道具时,打字稿告诉您这些道具在ProtectedRoute上不存在

您需要做的是正确定义ProtectedRoute的道具

interface Props {
  path: string;
  component: React.ComponentType<{}> // a class or function component which requires no props
}

class ProtectedRoute extends React.Component<Props> {

但是您似乎并没有真正使用道具path