“Получение данных с помощью React” Ответ

получить данные из API в React

useEffect(() => {
    const url = "https://api.adviceslip.com/advice";

    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const json = await response.json();
        console.log(json);
      } catch (error) {
        console.log("error", error);
      }
    };

    fetchData();
}, []);
Frail Fly

Реагировать метод получить

/* React get method.  */

componentWillMount(){
    fetch('/getcurrencylist',
    {
        /*
        headers: {
          'Content-Type': 'application/json',
          'Accept':'application/json'
        },
        */
        method: "get",
        dataType: 'json',
    })
    .then((res) => res.json())
    .then((data) => {
      var currencyList = [];
      for(var i=0; i< data.length; i++){
        var currency = data[i];
        currencyList.push(currency);
      }
      console.log(currencyList);
      this.setState({currencyList})
      console.log(this.state.currencyList);
    })
    .catch(err => console.log(err))
  }
Enthusiastic Elephant

Получение данных с помощью React

// mycomponent.js
import React, { useEffect, useState} from 'react';
import axios from 'axios';

const MyComponent = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([])

  useEffect(() => {
    const fetchData = async () =>{
      setLoading(true);
      try {
        const {data: response} = await axios.get('/stuff/to/fetch');
        setData(response);
      } catch (error) {
        console.error(error.message);
      }
      setLoading(false);
    }

    fetchData();
  }, []);

  return (
    <div>
    {loading && <div>Loading</div>}
    {!loading && (
      <div>
        <h2>Doing stuff with data</h2>
        {data.map(item => (<span>{item.name}</span>))}
      </div>
    )}
    </div>
  )
}

export default MyComponent;
serge kalaga

Ответы похожие на “Получение данных с помощью React”

Вопросы похожие на “Получение данных с помощью React”

Больше похожих ответов на “Получение данных с помощью React” по JavaScript

Смотреть популярные ответы по языку

Смотреть другие языки программирования