【问题标题】:how can my call the action in my component using typescript with react redux?如何使用带有 react redux 的 typescript 调用组件中的操作?
【发布时间】:2019-08-17 21:09:28
【问题描述】:

每当我从我的组件调用我的操作时,它都会向我显示错误。我正在使用带有 react redux 的打字稿。

错误:属性“getItem”不存在于类型“Readonly & Readonly'。

MY Action

import * as actionTypes from "../types";
import { getItems } from "../api/allApi";

export const getItem = () => {
  const payload = getItems();

  return {
    type: actionTypes.GET_ITEM,
    payload
  };
};

My Component

import React from "react";
import "../styles/settings.scss";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { getItem } from "../Actions/action";

class Settings extends React.Component {
  componentDidMount() {
    this.props.getItem(); // error here: Property 'getItem' does not exist on //type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'.ts(2339)
  }
  render() {
    return (
      <div>

              {console.log(this.props.items)} // Error here: Property 'items' //does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'
              {/* {console.log("asda", this.props.items)} */}
       </div>
    );
  }
}

const mapStateToProps = (state: any) => {
  return {
    items: state.getItemsReducer
  };
};

const mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({ getItem }, dispatch);
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Settings);

【问题讨论】:

  • 另外,最好不要留下很多any's。例如mapStateToProps 的返回类型是IPropsPartial&lt;IProps&gt;,如果你决定填充更多的道具。此外,它的状态应该是state:{ getItemsReducer: soneType[]}。不确定实际输出,但您可以弄清楚...

标签: reactjs typescript redux


【解决方案1】:

您需要创建道具并将它们传递给您的组件。这个道具应该包括getItms: Function。您是在告诉组件渲染他不知道存在的子集合。

你可以这样做:

export interface IProps {getItems: Function, Items:any[]} //See if you can figure out the type here

export class ComponentName extends Component<IProps, {}> {
 ...rest of the code here
}

【讨论】:

  • 谢谢@Dimitris 现在我可以调用我的任何操作了,我也可以在我的控制台中从 api 获取数据,但现在我没有获取要在屏幕上呈现的数据。如何从 api 访问数据以示例对象并希望访问其子对象数组。
  • 如果this.props.items, 打印在控制台中,您应该能够以相同的方式在您的渲染方法中使用它。现在,根据项目是什么(对象或对象数组),您可以通过它们进行映射。例如:this.props.items.map(item =&gt; do something here)。您应该可以在屏幕上打印它。只要确保你也传递了一个密钥。可能是项目的索引,或者其他独特的东西..
【解决方案2】:

您应该为组件Settings 创建道具(和状态)的接口。

interface ISettingsProps { 
  items: [] | {} //whatever may be the datatype.
  getItem(): void
}

并像这样传递给类

class Settings extends React.Component&lt;ISettingsProps&gt; {...}

【讨论】:

    猜你喜欢
    • 2020-05-30
    • 2019-10-23
    • 1970-01-01
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 2019-11-19
    • 2018-07-16
    相关资源
    最近更新 更多