.map() , Undefined 不是 React Native 中的函数

Posted

技术标签:

【中文标题】.map() , Undefined 不是 React Native 中的函数【英文标题】:.map() , Undefined is not a function in React Native 【发布时间】:2017-10-26 03:07:23 【问题描述】:

所以我调用了一个 API 并使用它来设置状态。

我的状态:

  state = 
   candlesticks: []
;

我的 API 调用和承诺函数:

componentDidMount() 
    axios
      .get(
    "apiurl"
      )
      .then(data => 
        let mappedData = data.map((record) => record.date *= 1000); //getting the error here with the map()function
        this.setState(
          candlesticks: mappedData
        );
      );
  

我尝试了不同的代码变体,但仍然出现此错误。 我正在使用 Expo 框架。

undefined 不是函数 (评估 'data.map(function (record)record.date *= 1000)')

【问题讨论】:

可能你必须从响应中解析data。这可能类似于data.body.mapdata.content.map。打印data 看看它到底包含什么! 我以前在网上使用过同样的数据,所以我知道。不过我当时用的是jQuery。 【参考方案1】:

Axios 返回一个response 对象。在响应中,您有一个包含数据的数据属性。 所以你需要做的是:

componentDidMount() 
    axios.get("apiurl")
    .then(response => 
        let mappedData = response.data.map((record) => record.date *= 1000); //getting the error here with the map()function
        this.setState(
            candlesticks: mappedData
        );
    );

编辑

似乎不太可能是axios有问题,只是为了排除,尝试使用内置的fetch模块,看看数据是否仍然为空。

componentDidMount() 
    fetch("apiurl")
    .then(response => 
        return response.json();
     )
    .then(data => 
        let mappedData = data.map((record) => record.date *= 1000);
        this.setState(
            candlesticks: mappedData
        );
    );

如果它为空,那么问题出在您的服务器上。

【讨论】:

我知道响应对象这是一个愚蠢的错误。谢谢。 虽然响应对象返回的数据都是null 我该如何解决这个问题? 我之前在 web 上使用 jQuery 时,同样的地图方法和数据也有效。 不应用map()方法时数据正确返回。

以上是关于.map() , Undefined 不是 React Native 中的函数的主要内容,如果未能解决你的问题,请参考以下文章

.map() , Undefined 不是 React Native 中的函数

ReactJs:::Cannot read property 'map' of undefined

Cannot read property 'map' of undefined

undefined-is-not-an-object-evaluate-this-state-datasource.map

尝试使用函数结果时出错,typeError: Cannot read property 'map' of undefined in React

我在我的 React 项目中收到此错误“TypeError: Cannot read property 'map' of undefined”