【问题标题】:Cannot read value of property after ajax requestajax请求后无法读取属性值
【发布时间】:2018-05-23 15:55:32
【问题描述】:

我的代码如下所示:

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

public componentWillMount() {
    this.getData();
}

public getData = () => {   
        axios.get(someURL)
        .then( (response) => {
            this.setState({list: response.data.arrivals});
        })
        .catch( (error) => {
            console.log("FAILED", error);
        });
}

public render(): JSX.Element {
    const {list}: any = this.state;
    const data: IScheduler = list;

    console.log("TEST");

    console.log(data); //cannot get data here

    console.log("TEST");

    return (
        <div className="main-page-container">
            <ArrivalsTable data={data}/>
        </div>
    );
}

我的问题是我无法读取我的数据。

 console.log(data);

给我一​​个数组:

length: 0
__proto__: Array(0)

 console.log(data.generatedDate);

给予:

 undefined

我的数据样本(已修改):

{
   "arrivals": [
       {
          "generatedDate": "03.12.2017"
       }
        ...
    ]
}

我想知道如何解决这个问题。有人可以帮忙吗?

(试图解决这个问题,但我仍然无法在 render() 中获取数据)

还有其他方法可以从 URL 中获取数据并将其放入属性中吗?

【问题讨论】:

  • 尝试在您的回复中添加console.log。您是否看到.then() 中的数据返回?
  • @Stuart Casarotto,是的
  • .then 方法中执行console.log(response); 会得到什么?
  • 我收到一个状态为 200 的响应和一个包含我的数据的数组。
  • 在您的render() 中尝试console.log(list)

标签: ajax reactjs typescript axios


【解决方案1】:

getData 应该如下

axios.get(someURL)
    .then((response) => {
        this.setState({list: response.data.arrivals});
    })
    .catch( (error) => {
        console.log("FAILED", error);
    });
}

注意this.setState({list: response.data.arrivals}); 部分。

【讨论】:

  • 哦。你说得对!也许你知道为什么我无法在 render() 中获取数据吗?
  • 你能发布你完整的 render() 方法吗?
  • 修改 const {list}: any = this.state; as const {list}: any = this.state.list;在 render() 方法中
  • 我收到一个错误:属性“列表”不存在于类型“只读”
  • 我的错。它应该是 const list: any = this.state.list;如果这不起作用,请在 render() 方法的顶部添加 console.log(this.state) 并查看 state 对象内部的内容
猜你喜欢
  • 2019-09-10
  • 1970-01-01
  • 2021-08-23
  • 2021-12-10
  • 1970-01-01
  • 2015-03-29
  • 1970-01-01
  • 2017-04-06
  • 2021-12-16
相关资源
最近更新 更多