“location”属性在类型为“Readonly<{}>”上不存在 - React Router和Typescript

3

我正在尝试创建一个用于身份验证的受保护路由。文档中建议使用ProtectedRoute组件,代码如下:

interface ProtectedRouteProps {
  auth: AuthState;
}

const ProtectedRoute = ({
  children,
  auth,
  ...rest
}: RouteProps & ProtectedRouteProps): JSX.Element => {
    console.log(auth)
  return (
    <Route
      {...rest}
      render={(props: RouteProps) =>
        auth.isAuthenticated ? children : <Redirect to={{pathname: "/signin", state: "Please sign in" }} />
      }
    />
  );
};

export default ProtectedRoute;

我随后使用它,并且想要展示状态(“请登录”),如果有人被重定向到登录页面。

我有一个包装组件用于处理路由:

export interface IWrapper {
    auth: AuthState
}

class Wrapper extends Component<IWrapper> {
    constructor(props: IWrapper){
        super(props);
        console.log(props)
    }
  render() {

    return (
      <div>
        <BrowserRouter>
          <HeaderContainer />
          <Switch>
          <Route exact path="/">
              <Home />
          </Route>
          <Route exact path="/signup">
            <SignUpView />
          </Route>
          <ProtectedRoute auth={this.props.auth} path="/dashboard">
              <DashboardContainer />
          </ProtectedRoute>
          </Switch>
          <Route exact path="/" component={Home}></Route>
          <Route exact path="/signout" component={SignUpView}></Route>
          <Route exact path="/signin" component={SignIn}></Route>

        </BrowserRouter>
      </div>
    );
  }
}

const mapStateToProps = (state: AppState) => ({
    auth: state.auth
})

export default connect(mapStateToProps)(Wrapper)

这是我的登录页面:

export default class SignIn<RouteComponentProps> extends Component {
    constructor(props: RouteComponentProps){
        super(props);
        console.log(props);
    }


    render() {
        return (
            <div>
                {this.props.location.state ? (
                    <h2>You were redirected</h2>
                ) : ("")}
                <SignInForm />
            </div>
        )
    }
}

在 TypeScript 编译器中,我无法使用 props.location,因为“属性‘location’不存在于类型‘Readonly<{}> & Readonly<{ children?: ReactNode; }>’中。”

对于 RouteComponentProps 的类型定义,我真的不理解这是什么意思:

export interface RouteComponentProps<Params extends { [K in keyof Params]?: string } = {}, C extends StaticContext = StaticContext, S = H.LocationState> {
  history: H.History;
  location: H.Location<S>;
  match: match<Params>;
  staticContext?: C;
}

那么问题在哪里呢?我已经尝试使用Redirect props,但也不起作用。我对Typescript是个新手,如果有人能帮忙就感激不尽了。谢谢。

1个回答

3

没有读完你的代码,我的猜测是你只需将SignIn类定义更改为

export default class SignIn<RouteComponentProps> extends Component { ... }

to

export default class SignIn extends Component<RouteComponentProps> { ... }

一般来说,泛型类型参数是在类名后面进行注释的,但在您的情况下不需要。在“extends”子句中,设置要扩展的组件的具体类型参数。如果只写extends Component并且没有通过Component<RouteComponentProps>指定props类型,则会使用Component的默认类型{},并且TypeScript无法在普通对象文字{}上找到location属性。

有关泛型类的更多信息,请参见此处


1
搞定了!太棒了,谢谢。 - Raph117

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接