3

所以我调用了一个 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})')

4

1 回答 1

2

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

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模块,看看数据是否仍然为null。

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

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

于 2017-05-25T13:26:14.233 回答