javascript - 如何在 react-redux-typescript 中传递 props

标签 javascript reactjs typescript redux react-redux

我正在尝试弄清楚如何在使用 typescript 时将 Prop 传递给组件。

如果我尝试在任何地方传递任何 prop,无论是本地状态还是除 {...this.props} 之外的任何东西,我都会收到错误消息.但是如果我传递 this.props,我在另一端得不到我想要的任何东西。相反,我得到了历史、位置、匹配它们适用的默认值和 staticContext: undefined。如果我尝试传递 Action ,如下面的示例所示,那么它将是未定义的。

结果我得到的错误是

client:157 [at-loader] ./src/containers/App/index.tsx:25:31 TS2339: Property 'actions' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Home> & Readonly<{ children?: ReactNode; }> & Read...'.

我的 App.tsx 如下:

import * as React from 'react';
import * as HomeActions from '../../actions/home';
import * as style from './style.css';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { RouteComponentProps } from 'react-router';
import { RootState } from '../../reducers';
import Home from '../../components/Home';

export namespace App {
  export interface Props extends RouteComponentProps<void> {
    actions: typeof HomeActions
  }

  export interface State {
    /* empty */
  }
}

export class App extends React.Component<App.Props, App.State> {

  render() {
    return (
      <div>
        <Home {...this.props} actions={this.props.actions}/>
        {this.props.children}
      </div>
    );
  }
}

function mapStateToProps(state: RootState) {
  return {
    home: state.home
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(HomeActions as any, dispatch)
  };
}

connect(mapStateToProps, mapDispatchToProps);

在 home 组件中,当我在 onComponentDidMount(){} 中记录 this.props.actions 时然后我得到未定义。

最佳答案

您应该将您的组件传递给 connect 并导出连接的组件,而不仅仅是组件。

export connect(mapStateToProps, mapDispatchToProps)(App);

关于javascript - 如何在 react-redux-typescript 中传递 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47599280/

相关文章:

reactjs - 从表单提交事件访问 typescript 中的 event.target.elements 属性

javascript - 类型 'allSettled' .ts(2339) 上不存在属性 'PromiseConstructor'

javascript - 通过更改 div 的 innerHtml 添加 DOM 元素可以防止稍后使用 getElementById 找到它吗?

javascript - MongoJS Node findOne 错误地没有返回结果

unit-testing - 当组件是无状态功能时,使用 Enzyme 按显示名称查找组件

php - Laravel + React,通过 Laravel 身份验证使用 api

javascript - 无法通过 chrome 扩展与 iFrame 交互

javascript - 在 vue.js 中获取 FormData 中的 null 值

javascript - 如何将时间格式化为 dayjs 对象?

node.js - MongoDB - 使用多个查找的 $group、辅助 $group、$sum 字段