如何在React中做出简单的api请求

时间:2019-04-20 18:17:53

标签: javascript ajax reactjs api

**嗨,我是应届毕业生,这是我对第一份工作的考验,希望我能得到它**

我要在此API端点 https://wainnakel.com/api/v1/GenerateFS.phpuid=26.2716025,50.2017993&g et_param=value

上获取请求

但它始终不返回任何内容,我确定我可以在浏览器上正确获取API

我感觉如何调用参数

{
    "error": "no",
    "name": "Al-Marsah Sea Food (المرساة للوجبات البحرية)",
    "id": "4d4c0573a33fb1f7c1bdb980",
    "link": "https://foursquare.com/v/4d4c0573a33fb1f7c1bdb980",
    "cat": "Seafood Restaurant",
    "catId": "4bf58dd8d48988d1ce941735",
    "rating": "8.8",
    "lat": "26.288311777445",
    "lon": "50.21692001999",
    "Ulat": "50.2017993",
    "Ulon": "26.2716025",
    "open": "",
    "image": [
        "https://fastly.4sqi.net/img/general/250x250/18198330_o4Ktyc-kd2fTED0JwALawq4AXOo44GjNIDtS_T9jHx0.jpg",
        "https://fastly.4sqi.net/img/general/250x250/25796514_zwYYGlX8eHKx5O5U6QBj-e1Aend4NQpxxcLsD5aHN8s.jpg"
    ]
}

我只从名字开始,然后我将采用

import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import "../../src/custom.scss";

class Map extends React.Component{
  constructor(props) {
  super(props);
    this.state = {
      error: null,
      isLoaded: false,
      UID: "lon" & "lat"  // محاولة name to value
    };
  }
componentDidMount() {
    fetch("https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value")     
     .then(res => res.json()) //I trid res.data.value , res.data.UID 
//the erorr is
// ^Unhandled Rejection (SyntaxError): Unexpected end of JSON input


      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            UID: result.UID
          });
        },
        console.log("2"),
        (error) => {
          console.log(error)
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
      console.log("3");

  }

render() {
    const { error, isLoaded, UID } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
        // console.log(fetch('https://wainnakel.com/api/v1/GenerateFS.php?uid=26.2716025,50.2017993&g et_param=value'));
      return (
          <div className="MapPage">
              <h2>maoop  </h2>

        <ul>
          {/* {items.map(item => (
            <li key={item.name}>
              {item.name} {item.price}
            </li>
          ))} */}
       <li>   {UID.name} </li>
        </ul>
        </div>
      );
    }
  }
}

export default Map;

谢谢!

0 个答案:

没有答案