【问题标题】:Call API with React Redux, Axios使用 React Redux、Axios 调用 API
【发布时间】:2019-12-17 02:20:22
【问题描述】:

抱歉我的英语和逻辑不好,我想使用 pokeapi.co 作为我的 Pokedex。

我的问题:我需要显示从 api 获取信息的道具。我可以在我的 axios 请求的 console.log(response) 中接收信息,但我无法在我的 Nav 组件的列表中显示它们,我的错误在哪里?

端点:https://pokeapi.co/api/v2/pokemon

我的代码:

App.js

// == 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

// == 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;

导航组件

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;


导航容器

// == 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

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;

怎么了?

谢谢!

【问题讨论】:

    标签: reactjs redux axios state


    【解决方案1】:

    感谢 @Meshack Mbuvi 私下的支持。

    • thunk的缺失是第一个问题

    • 以下代码解决了我的问题(感谢@Mbuvi):

          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);
            });
        };
    

    【讨论】:

      【解决方案2】:

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

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

      告诉我进展如何

      【讨论】:

        【解决方案3】:

        使用 Lodash

          {
              _.map(results, (Pokemon, index) => {
                  return (
                    <li key={Pokemon} className="menu-item">
                         {Pokemon}
                    </li>
                  )})
          }
        

        使用原生地图

         {
           results.map((Pokemon, index) => {
           return (
                 <li key={Pokemon} className="menu-item">
                    {Pokemon}
                 </li>
             )})
          }
        

        我想你忘记返回地图组件了。

        【讨论】:

        • 我应用了您的本地地图技术,但仍然无法使用地图组件是我的导航组件对吗?他在我的 App.js 上被调用我想从 data.response.results 接收 results 我在我认为的状态和道具之间迷路了..
        猜你喜欢
        • 2019-10-02
        • 2016-07-21
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 2019-02-21
        • 2018-11-14
        • 2023-04-10
        • 2020-03-13
        相关资源
        最近更新 更多