使用React访问TypeScript类的字段

问题描述 投票:1回答:3

我正在使用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

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

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

先感谢您 !!!

reactjs typescript axios
3个回答
1
投票

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


0
投票

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


0
投票

我同意Barazu。让我对问题采取不同的方法。您要获取的数据字段本身是“行”类型。我已经稍微调整了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不是'data'上的字段或属性,但'data'是'Row []'类型。

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

const myRows: Row[] = this.state.data;
for (const row of myRows) { console.log(myRow[0]); }
© www.soinside.com 2019 - 2024. All rights reserved.