首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用,Axios调用API

用,Axios调用API
EN

Stack Overflow用户
提问于 2019-12-17 02:20:22
回答 3查看 239关注 0票数 0

对不起,我的英语不太好,逻辑也不太好,我想用pokeapi.co作为我的索引。

我的问题是:我需要显示来自api的信息内容的道具。我可以在我的console.log(响应)中接收到有关axios请求的信息,但是我不能将它们显示在Nav组件的列表上,我的错误在哪里?

endPoint:https://pokeapi.co/api/v2/pokemon

我的代码:

App.js

代码语言:javascript
复制
// == Import : npm
import React from 'react';

// == Import : local
import Home from 'src/components/Home';
import Nav from 'src/containers/Nav';
import './app.scss';


// == Composant
const App = results => (
  <div id="app">
    <nav className="nav">
      <Nav props={results} />
    </nav>
    <main className="content">
      <Home />
    </main>
    )}
  </div>
);

// == Export
export default App;

reducer.js

代码语言:javascript
复制
// == Initial State

const initialState = {
  results: [],
  name: '',
  url: '',
};

// == Types
export const FETCH_POKEMON_API = 'FETCH_POKEMON_API';
const RECEIVE_POKEMON_LIST = 'RECEIVE_POKEMON_LIST';

// == Reducer
const reducer = (state = initialState, action = {}) => {
  // console.log('une action arrive dans le reducer', action);
  switch (action.type) {
    case RECEIVE_POKEMON_LIST:
      return {
        ...state,
        results: action.results,
      };

    default:
      return state;
  }
};

// == Action Creators
export const fetchPokemonApi = () => ({
  type: FETCH_POKEMON_API,
});

export const receivePokemonList = results => ({
  type: RECEIVE_POKEMON_LIST,
  results,
});


// == Selectors


// == Export
export default reducer;

Nav组件

代码语言:javascript
复制
import React from 'react';
import PropTypes from 'prop-types';
// import { NavLink } from 'react-router-dom';

// import { getUrl } from 'src/utils';
import './nav.scss';

const Nav = ({ results }) => {
  console.log('if i receive my props from PokeAPI its win guys', results);
  return (
    <div className="menu">
      {results.map(({ Pokemon }) => (
        <li key={Pokemon} className="menu-item">
          {Pokemon}
        </li>
      ))}
    </div>
  );
};

Nav.propTypes = {
  results: PropTypes.arrayOf(
    PropTypes.shape({
      name: PropTypes.string.isRequired,
    }),
  ).isRequired,
};
export default Nav;

Nav容器

代码语言:javascript
复制
// == Import : npm
import { connect } from 'react-redux';

// == Import : local
import Nav from 'src/components/Nav';

// === State (données) ===
const mapStateToProps = state => ({
  results: state.results,
});

// === Actions ===
const mapDispatchToProps = {};

// Container
const NavContainer = connect(
  mapStateToProps,
  mapDispatchToProps,
)(Nav);

// == Export
export default NavContainer;

axiosMiddleware

代码语言:javascript
复制
import axios from 'axios';

import { FETCH_POKEMON_API, receivePokemonList } from 'src/store/reducer';

const ajaxMiddleware = store => next => (action) => {
  console.log('L\'action suivante tente de passer', action);
  switch (action.type) {
    case FETCH_POKEMON_API:
      axios.get('https://pokeapi.co/api/v2/pokemon')
        .then((response) => {
          console.log('response', response);
          console.log('response.data', response.data);
          console.log('response.data.results', response.data.results);

          const { data: results } = response;
     this.setState({
            results: response.data.results,
          });
          store.dispatch(receivePokemonList(results));
        })
        .catch(() => {
          console.log('Une erreur s\'est produite');
        });
      break;

    default:
      // console.log('action pass', action);
      next(action);
  }
};

export default ajaxMiddleware;

出什么事了?

谢谢你!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-12-17 13:26:45

我认为代码失败了,因为最初,结果是未定义的(在调用API之前)。另外,Nav组件要求result对象应该有一个名为name的属性。让您的初始状态如下:

代码语言:javascript
复制
const initialState = {
   results: [{name:""}],
   name: '',
   url: '',
};

让我知道是怎么回事

票数 0
EN

Stack Overflow用户

发布于 2019-12-17 16:26:18

感谢@Meshack Mbuvi私下里的支持。

  • thunk的脓肿是
  • 的第一个问题下面的代码解决了我的问题(感谢@Mbuvi ) :

代码语言:javascript
复制
      axios.get('https://pokeapi.co/api/v2/pokemon')
        .then((response) => {
          console.log('response.data.results', response.data.results);
          // ici je défni pokemons from api, qui contient la list des pokemons
            // It was like this: const {results} = response.data.results
          const { results } = response.data; // The error was here
          dispatch(receivePokemonList(results));
        })
        .catch((err) => {
          console.log('Une erreur s\'est produite', err);
        });
    };
票数 1
EN

Stack Overflow用户

发布于 2019-12-17 02:30:14

使用Lodash

代码语言:javascript
复制
  {
      _.map(results, (Pokemon, index) => {
          return (
            <li key={Pokemon} className="menu-item">
                 {Pokemon}
            </li>
          )})
  }

使用本地地图

代码语言:javascript
复制
 {
   results.map((Pokemon, index) => {
   return (
         <li key={Pokemon} className="menu-item">
            {Pokemon}
         </li>
     )})
  }

我想你忘了还地图组件了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59366760

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档