在反应功能组件中设置和访问道具

时间:2019-08-19 14:00:55

标签: reactjs typescript react-redux

我正在尝试在React功能组件中访问redux存储变量。下面的代码

import React from "react";
import { connect } from "react-redux";
import {
  Redirect,
  Route,
  RouteComponentProps,
  RouteProps
} from "react-router-dom";
import { Wizard } from "../models/wizard";
import { IStoreState } from "../redux/reducers/index";
import { WizardStage } from "../models/enums";
import { PrivateRoute } from "./PrivateRoute";
import { GettingStarted } from "./GettingStarted";

interface IWizardRouteProps extends RouteProps {
  wizard: Wizard;
}

export const _WizardRoute = ({ component, ...rest }: IWizardRouteProps) => {
  if (!component) {
    throw Error("component is undefined");
  }

  const Component = component;

  const render = (props: RouteComponentProps<any>): React.ReactNode => {

    **if (props.wizard.wizardStage===WizardStage.InProgress) {
      return <PrivateRoute {...props} component={Component} />;
    }**

    return (
      <PrivateRoute
        exact
        path="/quote/getting-started"
        component={GettingStarted}
      />
    );
  };

  return <Route {...rest} render={render} />;
};

const mapStateToProps = ({
  wizard
}: IStoreState): {
  wizard: Wizard;
} => {
  return { wizard };
};

export const WizardRoute = connect(
  mapStateToProps,
  null
)(_WizardRoute);

不确定我缺少什么。我似乎无法从存储在if条件中的代码中访问向导,并获得编译时错误。出现以下错误,

Property 'wizard' does not exist on type 'RouteComponentProps<any, StaticContext, any>'.ts(2339)

有什么建议吗?

更新

Chris Heald的建议奏效了。但是现在我收到以下错误。还将代码更改为类组件。我将向导作为道具传递

import React from "react";
import { Redirect, Route, RouteProps } from "react-router-dom";
import { Wizard } from "../models/wizard";
import { WizardStage } from "../models/enums";
interface IPrivateWizardRouteProps {
  wizard: Wizard;
}
export class PrivateWizardRoute extends React.Component<
  IPrivateWizardRouteProps & RouteProps
> {
  renderThis = (props: any) => {
    if (this.props.wizard.wizardStage === WizardStage.InProgress) {
      return <React.Component {...props} />;
    } else {
      debugger;
      return (
        <Redirect
          to={{
            pathname: "/quote/getting-started"
          }}
        />
      );
    }
  };
  render() {
    const { path, exact } = this.props;
    console.log(this.props);
    return (
      <Route
        path={path}
        exact={exact}
        render={props => this.renderThis(props)}
      />
    );
  }
}
export default PrivateWizardRoute;

enter image description here

1 个答案:

答案 0 :(得分:0)

Typescript抱怨您的props(定义为RouteComponentProps)不希望使用名为wizard的属性。如果您查看type definition,显然不会!

您应该能够让您的函数期望一个由RouteComponentPropsIWizardRouteProps组成的新接口:

const render = (props: RouteComponentProps<any> & IWizardRouteProps)

顺便说一句,您可能应该使用useCallback来定义渲染功能,而不是仅仅就地定义它。否则,您将在每次渲染组件时重新定义该函数。