mapStateToProps OwnProps 参数包含在高阶组件中未定义的属性 [英] mapStateToProps OwnProps argument contains a property that is undefined in Higher Order Component

查看:46
本文介绍了mapStateToProps OwnProps 参数包含在高阶组件中未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的 react-redux 用户,尝试将高阶组件连接到 react-redux 存储.在映射状态到 props 函数中,我使用 ownProps 参数来过滤状态.但是,我尝试在 OwnProps 中使用的属性始终未定义.有没有人遇到过类似的情况?

I am new react-redux user trying to connect a higher order component to react-redux store. In the map state to props function I am using ownProps argument for filtering the state. However, the property that I am trying to use within OwnProps is always undefined. Has anyone experienced something similar?

Redux 属性

import { connect } from "react-redux";

import { clearErrorAction } from "../features/errors/actions";
import { filterErrors } from "../features/errors/selectors";
import { FailureNotify } from "../features/errors/types";
import { HocComponentProps } from "./types";
import { RootState } from "typesafe-actions";

type StateProps = {
  error: FailureNotify[];
};

export const mapStateToProps = (
  state: RootState,
  ownProps: HocComponentProps
): StateProps => {
  // uniqueId property is always undefined here???
  console.log(`withErrorListener mapStateToProps => ${ownProps.uniqueId}`);
  return {
    error: filterErrors(state.errors as StateProps, ownProps)
  };
};

export const dispatchProps = {
  clearError: clearErrorAction
};

export const connector = connect(
  mapStateToProps,
  dispatchProps
);

高阶组件

import * as React from "react";

import { ConnectedProps } from "react-redux";
import { RouteComponentProps, withRouter } from "react-router-dom";

import { connector } from "./redux";
import { FailureNotify } from "../features/errors/types";

/**
 * Type declarations
 */
type ReduxProps = ConnectedProps<typeof connector>;
type ExpectedProps = { uniqueId: string };

/**
 * Internal components
 */
type ErrorInfoProps = { info: FailureNotify } & ReduxProps &
  RouteComponentProps;
const ErrorInfo = ({
  info,
  clearError,
  history
}: ErrorInfoProps): JSX.Element => {
  function goHome(): void {
    console.log("Go home button has been clicked");
    clearError(info.fromAction, info.fromComponent, history, "/");
  }
  return (
    <React.Fragment>
      <p>Error {info.message}</p>
      <p>Received from action {info.fromAction}</p>
      <p>Received for component id {info.fromComponent}</p>
      <button onClick={goHome}>Home</button>
    </React.Fragment>
  );
};

/**
 * HoC that renders errors on the redux store rasied for a component.
 * @param BaseComponent  The component to wrap should have uniqueId property
 */
export const withErrorListener = <BaseProps extends ExpectedProps>(
  BaseComponent: React.ComponentType<BaseProps>
) => {
  /**
   * Type declarations
   */
  type HocProps = BaseProps & ReduxProps & RouteComponentProps;

  class ErrorListener extends React.Component<HocProps, {}> {
    static displayName = `withErrorListener(${BaseComponent.name})`;
    static readonly WrappedComponent = BaseComponent;

    /**
     * Render error if there is one to display, otherwise render the base component
     * @returns Rendered error if error occurred. Rendered base component if no error occurred.
     */
    render() {
      const { ...restProps } = this.props;
      console.log(`withErrorListener [error_count=${this.props.error.length}]`);
      if (this.props.error.length > 0) {
        return <ErrorInfo info={this.props.error[0]} {...restProps} />;
      } else {
        return <BaseComponent {...restProps as BaseProps} />;
      }
    }
  }

  const ConnectedHoc = connector(ErrorListener as any);
  const RoutedHoc = withRouter(ConnectedHoc as any);

  return RoutedHoc;
};

我在此源文件

I am creating an instance of the withErrorListener higher order component at the end of this source file

const PostsListConnectedWithId = connector(withId(PostsListBase));
export const PostsListWithErrorListener = withErrorListener(
  PostsListConnectedWithId
);

PostsListBase 的源代码在同一个 源文件

PostsListsWithErrorListener 呈现在 应用组件.

始终未定义的属性是uniqueId,并由withId 高阶组件此处.代码和框中的控制台日志输出显示了 uniqueId 属性值.

The property that is always undefined is uniqueId and is injected into the base component by the withId higher order component, here. The console log output within the codesandbox shows the uniqueId property value.

推荐答案

在问了另一个问题后设法让这个工作正常运行 此处.

Managed to get this working, after asking another question here.

问题是错误地将 HoC 连接到 redux 存储的混合,即组件被强制转换为任何.此问题已在单独的问题.

The issue was a mixture of incorrectly connecting the HoC to redux store, i.e. component was casted to any. This issue was solved in a separate question.

其中一条评论表明 uniqueId 属性没有被初始化.我重构了 withErrorListener HoC 以注入 uniqueId 属性,以便它自动分配,而无需开发人员指定.

One of the comments suggested that the uniqueId property was not being initialised. I refactored the withErrorListener HoC to inject the uniqueId property so that it is automatically assigned without the developer having to specify.

可以找到codesandbox模型这里

A codesandbox model can be found here

如果评论者希望提出 uniqueId 属性未初始化的答案,那么我会接受.

If the commenter wishes to suggest an answer that the uniqueId property was not initialised then I will accept it.

这篇关于mapStateToProps OwnProps 参数包含在高阶组件中未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆