javascript - React - 使用外部 URL 时未定义 Map 函数

标签 javascript arrays json reactjs axios

我收到常见错误.map 不起作用。仅当我使用外部 api url 时才会发生该错误,同时当我在浏览器中打开 url 并将 json 数据复制到本地文件并通过 ajax 调用它时,它工作得很好。我认为 JSON 响应中有错误。我想不通。

请检查下面的代码。当我将 url1 传递给 axios 时,出现错误,当我将 url2 传递给 axios 时,数据打印得很好。

class Products extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      products: []
    }
  }
  getProducts(){
    const url1="https://anagha.herokuapp.com/anagha-all-products/100";
    const url2 = "https://quarkbackend.com/getfile/sivadass/anagha-products";
    axios.get(url2)
      .then(response => {
        this.setState({
          products : response.data
        }, function(){
          console.log(this.state.products)
        })
      })
  }
  componentWillMount(){
    this.getProducts();
  }
  render(){
    var productsList = this.state.products.map(function(data) {
      return (
        <li>{data.title}</li>
      );
    });
    return(
        <ul>{productsList}</ul>
    );
  }
}

这是link到工作演示

最佳答案

收到json响应后,我使用JSON.parse解析它,然后错误被清除。

const url1="https://anagha.herokuapp.com/anagha-all-products/100";
axios.get(url1)
  .then(response => {
    let parsedData = JSON.parse(response.data);
    this.setState({
      products : parsedData
    }, function(){
      console.log(this.state.products)
    })
  })

关于javascript - React - 使用外部 URL 时未定义 Map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45396748/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

javascript - 将函数数组作为参数传递

javascript - Canvas (fabricjs) 阻止网络浏览器在手机上缩放和移动

java - 我的数组元素在 Java 中具有相同的 id?

c++ - 二维字符数组上的 memset

javascript - 使用 for 循环中的 for 循环将对象从图 api json 插入数组(facebook javascript sdk/open graph)

json - 执行错误,从 org.apache.hadoop.hive.ql.exec.DDLTask 返回代码 1。 com/mongodb/util/JSON

json - 转换 json 文件

javascript - JS事件查看Mobile Safari是否已关闭?

javascript - Socket.io.js - 授权时拒绝连接后仍然建立连接