【问题标题】:React - Map function is not defined when using an external URLReact - 使用外部 URL 时未定义地图功能
【发布时间】:2018-01-05 21:30:23
【问题描述】:

我收到常见错误 .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 工作演示

【问题讨论】:

    标签: javascript arrays json reactjs axios


    【解决方案1】:

    收到 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)
        })
      })
    

    【讨论】:

      猜你喜欢
      • 2019-04-23
      • 2021-09-28
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多