React + Axios - Карта возвращает не функция? - PullRequest
0 голосов
/ 18 декабря 2018

Я работаю над своим первым API с React.Я могу сохранить в журнале мое текущее состояние после его загрузки и установки состояния для этого массива.Тем не менее, запуск моего компонента с подпоркой «FragrancesArray», установленной после загрузки данных из this.state.fragrances, возвращает не функцию.

Использование axios async и await.

Понятия не имеюЗачем?Может кто-нибудь помочь?

Спасибо.

Мой код:

// Core React
import React, { Component } from 'react';

// Axios
import axios from 'axios';

// Constants
import { FRAGRANCES_URL, BLOGS_URL, MAKE_UP_URL } from 'constants/import';

// Components
import Fragrances from 'components/Fragrances/Fragrances';

class App extends Component {

  state = {
    fragrances: [],
    blogs: [],
    makeup: []
  }

  getCoffee() {
    return new Promise(resolve => {
      setTimeout(() => resolve('☕'), 0); // it takes 1 seconds to make coffee
    });
  }

  async showData() {
    try {
      // Coffee first
      const coffee = await this.getCoffee();
      console.log(coffee); // ☕

      // Axios API's
      const fragranceData = axios(FRAGRANCES_URL);
      const blogData = axios(BLOGS_URL);
      const makeupData = axios(MAKE_UP_URL);

      // await all three promises to come back and destructure the result into their own variables
      await Promise.all([fragranceData, blogData, makeupData])

      .then((data) => {
        this.setState({
          fragrances: data[0],
          blogs: data[1],
          makeup: data[2]
        });

        const { blogs } = this.state;
        console.log(blogs);
      })

    } catch (e) {
      console.error(e); // ?
    }

  }

  componentDidMount() {
    this.showData();
  }

  render() {
    return (
      <Fragrances FragranceArray={this.state.fragrances} AppURL={FRAGRANCES_URL} />
    )
  }
}
export default App;

1 Ответ

0 голосов
/ 18 декабря 2018

В реакции, прежде чем вы сможете установить / использовать состояние, вам нужно объявить его с помощью getInitialState(), но с моделью класса ES6 вы инициализируете состояние в конструкторе.

class App extends Component {

  constructor(props) {
    super(props)
    //- Initialize default state values
    this.state = {
      fragrances: [],
      blogs: [],
      makeup: []
    }
  }
  
  //The rest of code stays the same.

    render() {
    return (
      <Fragrances FragranceArray={this.state.fragrances} AppURL={FRAGRANCES_URL} />
    )
  }
}

Подробнее о состоянии реакции

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...