【问题标题】:How to pass props down in react-redux-typescript如何在 react-redux-typescript 中传递道具
【发布时间】:2017-12-01 18:19:20
【问题描述】:

我想弄清楚在使用打字稿时如何将道具传递给组件。

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

我得到的错误是

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 时,我会得到未定义。

【问题讨论】:

  • 你有什么解决办法吗?

标签: javascript reactjs typescript redux react-redux


【解决方案1】:

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

export connect(mapStateToProps, mapDispatchToProps)(App);

【讨论】:

  • 我重构了以下内容,应该早点完成,所以谢谢。但是,当我尝试传入新的道具(样式、类名、动作、任何东西)时,我仍然收到与上述相同的错误。
猜你喜欢
  • 2021-04-01
  • 1970-01-01
  • 2021-09-08
  • 2021-07-21
  • 2018-02-03
  • 2018-06-28
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多