React函数组件访问Redux Store变量报错及类组件改造问题咨询
问题分析与解决方案
第一个函数组件问题:无法访问Redux Store中的wizard,编译报错Property 'wizard' does not exist on type 'RouteComponentProps<any...>'
你这里混淆了两个不同的props来源:render函数参数里的props是React Router传递的路由相关属性,而从Redux获取的wizard是通过connect注入到_WizardRoute组件自身的props,并不是路由props的一部分。
修正方法很简单,直接使用组件自身props里的wizard即可,不要从路由渲染参数里取:
export const _WizardRoute = ({ component, wizard, ...rest }: IWizardRouteProps) => { if (!component) { throw Error("component is undefined"); } const Component = component; const render = (props: RouteComponentProps<any>): React.ReactNode => { // 这里用组件自身的wizard prop,不是路由props里的 if (wizard.wizardStage === WizardStage.InProgress) { return <PrivateRoute {...props} component={Component} />; } return ( <PrivateRoute exact path="/quote/getting-started" component={GettingStarted} /> ); }; return <Route {...rest} render={render} />; };
这样就能正确访问Redux中的wizard,编译错误也会消失。
第二个类组件的新问题:return <React.Component {...props} />;的错误
你这里犯了一个基础错误:React.Component是组件的基类,不是可直接渲染的React元素。你需要像之前的函数组件一样,接收要渲染的目标组件作为props,然后正确渲染它。
先修改props接口,补充component属性,再调整渲染逻辑:
import React from "react"; import { Redirect, Route, RouteProps, RouteComponentProps } from "react-router-dom"; import { Wizard } from "../models/wizard"; import { WizardStage } from "../models/enums"; // 扩展RouteProps,加入要渲染的组件和wizard interface IPrivateWizardRouteProps extends RouteProps { wizard: Wizard; component: React.ComponentType<RouteComponentProps<any>>; } export class PrivateWizardRoute extends React.Component<IPrivateWizardRouteProps> { renderThis = (props: RouteComponentProps<any>) => { const Component = this.props.component; if (this.props.wizard.wizardStage === WizardStage.InProgress) { // 渲染传入的组件,并传递路由props return <Component {...props} />; } else { return ( <Redirect to={{ pathname: "/quote/getting-started" }} /> ); } }; render() { const { path, exact, ...rest } = this.props; return ( <Route path={path} exact={exact} {...rest} render={props => this.renderThis(props)} /> ); } }
另外,别忘了如果这个类组件需要从Redux获取wizard,还是要用connect包装它:
import { connect } from "react-redux"; import { IStoreState } from "../redux/reducers/index"; // ... 上面的类组件代码 ... const mapStateToProps = ({ wizard }: IStoreState): { wizard: Wizard } => ({ wizard }); export default connect(mapStateToProps, null)(PrivateWizardRoute);
这样修改后,类组件就能根据wizard的状态正确渲染目标组件或执行重定向了。
内容的提问来源于stack exchange,提问作者Joshua
相关产品推荐
相关产品推荐

