【问题标题】:access to the fields of a class TypeScript with React使用 React 访问 TypeScript 类的字段
【发布时间】:2018-06-11 18:26:46
【问题描述】:

我正在使用 React、TypeScript 和 axios 处理 HTTP 请求。 当我执行 axios.get (myURL) 时,我会以这种格式获取数据:

[["value1","value2"],["value3","value4"],["value5","value6"]]

我创建了一个代表字符串数组的类。代码如下:

import  Serializable  from '../interface/serializable';

export default class Row {
    public row:string[];
}

这是我想在其中使用此类的组件的代码:

import Row from '../class/row';

interface IColumnSelectionState {
    readonly data: Row[],
}
    class MyDataextends React.Component<any,IColumnSelectionState>{

            constructor(props: any) {
                super(props);
                this.state = {
                    data: [],
                }
                this.submit = this.submit.bind(this);
            }

   private submit():void{
                axios.get("myURL").then(res => {
                    const response = res.data;
                    this.setState({ data: response });
                }).catch(error => {
                    console.log(error);
                })
            }
        }

我执行“submit()”方法时的问题:

 console.log (this.state.data) // I see my data in the format described    above

但是当我这样做时:

console.log (this.state.data [0].row) // this shows me undefined while I declared my array in the Row class

我真的需要得到第一个数组来循环它并进行处理。

如果有人知道如何做到这一点,谢谢你的帮助!

提前谢谢你!!!

【问题讨论】:

  • 是否需要在构造函数中初始化'this.state.data'?如果是这样,您应该为其分配一个新的 Row[],而不是 []。

标签: reactjs typescript axios


【解决方案1】:

显示的格式中没有row。日志中还有一个不必要的空间。
试试console.log(this.state.data[0];

【讨论】:

    【解决方案2】:

    它返回给我一个 Row 的实例。所以通常如果我这样做 "this.state.data [0] .row" 它应该向我发送一个字符串数组,因为 Row 有一个属性 "row: string []"

    【讨论】:

    • 看看你的格式。你在任何地方看到row 吗?重新格式化您正在获取的数据或按照我在回答中的指示访问它。再一次,注意你的空间!
    【解决方案3】:

    我同意巴拉祖的观点。让我对这个问题采取不同的方法。您返回的数据字段本身就是“行”类型。我已经稍微调整了 Axios 请求以进行演示。 (抱歉提前格式化)

               axios.get("myURL").then(res: AxiosResponse<Row> => { // added a type here to res
                    const response = res.data; // response is a Row[]
                    this.setState({ data: response });
                }).catch(error => {
                    console.log(error);
                })
    

    在这里,Axios 使用泛型来声明有效负载(数据字段)的类型为 Row 不是“数据”上的字段或属性,但“数据”的类型为“行[]”。

    我不确定你需要在哪里迭代这些数据,但我猜它是在组件的状态下。然后,一旦检索到数据,您应该能够执行此类操作

    const myRows: Row[] = this.state.data;
    for (const row of myRows) { console.log(myRow[0]); }
    

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 2021-10-22
      • 2021-09-01
      • 2020-12-25
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多