【问题标题】:trying to map an array out of backend API in REACT尝试从 REACT 中的后端 API 映射数组
【发布时间】:2023-04-01 11:32:01
【问题描述】:

单页工作正常,但是当我尝试在 JSON 中的平台数组或任何其他数组上进行映射时,我收到此错误(我知道错误在 useEffect 周围,但我看不到它通过)The error image
您可以在我的 Github 存储库github repo 中查看整个源代码

代码


这是数组 JSON

{
    "id": 1,
    "name": "Assassin's Creed",
    "genre": "Action-Adventure",
    "remastered": false,
    "poster": "https://i.ibb.co/gtFF78Q/ac1.jpg",
    "synopsis": "Desmond Miles, a bartender, is kidnapped by the company Abstergo Industries for use as a test subject in the 'Animus,' a device that can simulate genetic memory. Abstergo intends to put Desmond in the device to recall the memories of his ancestor, Altaïr Ibn-La'Ahad, a member of the Assassin Brotherhood in the year 1191, who lived during the Third Crusade in the Holy Land.",
    "developer": ["Ubisoft Montreal"],
    "release_date": "November 13, 2007",
    "publisher": "Ubisoft",
    "engine": "Scimitar",
    "composer": ["Jesper Kyd"],
    "ESRB_rating": "M (Mature)",
    "platforms": ["PlayStation 3", "Xbox 360", "Microsoft Windows"],
    "trailer": "https://www.youtube.com/watch?v=RjQ6ZtyXoA0",
    "website": "https://www.ubisoft.com/en-us/game/assassins-creed/assassins-creed"
  },

这是单页

import React, { useEffect } from 'react';
import Header from '../components/Header';
import { useParams } from 'react-router-dom';
import { useGlobalContext } from '../context';

const SingleGamePage = ({
  current,
  gameCurrent,
  setCurrent,
  setGameCurrent,
}) => {
  const { id } = useParams();
  const { singleGame, fetchSingleGame } = useGlobalContext();

  useEffect(() => {
    fetchSingleGame(id);
    let title = 'Games';
    document.title = `${title} | ${singleGame.name}`;
    setCurrent(title.toLowerCase());
    setGameCurrent(singleGame.name);
    // eslint-disable-next-line
  }, [singleGame.name, id]);
  const {
    name,
    poster,
    composer,
    developer,
    remastered,
    synopsis,
    ESRB_rating,
    platforms,
    engine,
    release_date,
    genre,
    publisher,
    trailer,
    website,
  } = singleGame;

  console.log(platforms);

  return (
    <React.Fragment>
      <Header current={current} gameCurrent={gameCurrent} />
      <section className='sm:p-8 p-4 bg-center bg-cover bg-no-repeat'>
        <div className='container sm:p-10 p-5 shadow-2xl rounded-lg opacity-100 bg-rgba'>
          <div>
            <div className='grid lg:grid-cols-2 grid-cols-1'>
              <div className='mx-auto lg:mx-0 w-64 sm:w-80'>
                <img
                  src={poster}
                  className='
                  rounded-lg
                  h-96
                  w-full
                  sm:h-single-image
                  border-4 border-light-hero
                '
                  alt={name}
                />
              </div>

              <div className='mx-auto lg:-ml-24 lg:mr-0 my-5 lg:my-0'>
                <h2
                  className='
                  text-4xl
                  sm:text-6xl
                  font-bold font-homenaje
                  tracking-widest
                  uppercase
                  sm:mt-0 sm:mb-4
                  mt-3
                  mb-6
                  text-hero
                '
                >
                  {name}
                  {remastered && (
                    <span
                      className='
                    inline-flex
                    text-lg
                    bg-gray-700
                    capitalize
                    font-normal
                    tracking-widest
                    sm:px-2 sm:py-1
                    px-1
                    py-0
                    rounded-md
                  '
                    >
                      remastered
                    </span>
                  )}
                </h2>
                <p
                  className='
                  font-roboto
                  text-gray-300
                  tracking-widest
                  font-bold
                  sm:text-3xl
                  text-xl
                  sm:mb-5
                  mb-6
                '
                >
                  {release_date}
                </p>
                <div
                  className='
                  font-roboto
                  capitalize
                  font-bold
                 tracking-widest
                  text-lighter-hero
                  sm:text-base
                  text-sm
                '
                >
                  <p className='my-1'>
                    genre :
                    <span
                      className='
                      text-light
                      sm:text-base
                      text-sm
                      font-normal
                      normal-case
                    '
                    >
                      {genre}
                    </span>
                  </p>
                  <p className='my-1'>
                    developer :
                    <span
                      className='
                      text-light
                      sm:text-base
                      text-sm
                      font-normal
                      normal-case
                    '
                    >
                      {`${developer},  `}
                    </span>
                  </p>
                  <p className='my-1'>
                    engine :
                    <span
                      className='
                      text-light
                      sm:text-base
                      text-sm
                      font-normal
                      normal-case
                    '
                    >
                      {engine}
                    </span>
                  </p>
                  <p className='my-1'>
                    publisher :
                    <span
                      className='
                      text-light
                      sm:text-base
                      text-sm
                      font-normal
                      normal-case
                    '
                    >
                      {publisher}
                    </span>
                  </p>
                  <p className='my-1'>
                    composer :
                    <span
                      className='
                      text-light
                      sm:text-base
                      text-sm
                      font-normal
                      normal-case
                    '
                    >
                      {`${composer},  `}
                    </span>
                  </p>
                  <p className='my-1'>
                    ESRB Rating :
                    <span
                      className='
                      text-light
                      sm:text-base
                      text-sm
                      font-normal
                      normal-case
                    '
                    >
                      {ESRB_rating}
                    </span>
                  </p>
                  <p className='my-1'>
                    synopsis :
                    <span
                      className='
                      text-light
                      sm:text-base
                      text-sm
                      font-normal
                      normal-case
                      synopsis
                    '
                    >
                      {synopsis}
                    </span>
                  </p>
                </div>
              </div>
            </div>
            <div className='w-full sm:my-6 my-0 py-5'>
              <p
                className='
                font-roboto
                capitalize
                font-bold
                tracking-widest
                text-lighter-hero
                sm:text-base
                text-sm
              '
              >
                Platforms :
                {platforms.map((pla) => {
                  return <span className='text-light'>{pla}</span>;
                })}
              </p>
              <p
                className='
                font-homenaje
                capitalize
                font-bold
                tracking-widest
                text-gray-600
                sm:text-base
                text-sm
                pt-8
                flex
                justify-around
                items-center
              '
              >
                <a
                  rel='noreferrer'
                  target='_blank'
                  href={trailer}
                  className='
                  bg-gray-800
                  rounded-lg
                  uppercase
                  inline-block
                  text-hero
                  sm:px-4 sm:py-2
                  px-2
                  py-1
                  sm:text-lg
                  text-sm
                  font-bold
                  hover:text-gray-800 hover:bg-hero
                  transition-colors
                  duration-700
                  ease-out
                '
                >
                  <i className='fab fa-youtube'></i> trailer
                </a>
                <a
                  rel='noreferrer'
                  target='_blank'
                  href={website}
                  className='
                  bg-gray-800
                  rounded-lg
                  uppercase
                  inline-block
                  text-hero
                  sm:px-4 sm:py-2
                  hover:text-gray-800 hover:bg-hero
                  px-2
                  py-1
                  sm:text-lg
                  font-bold
                  transition-colors
                  duration-700
                  ease-out
                  text-sm
                '
                >
                  <i className='fas fa-globe'></i> Website
                </a>
              </p>
            </div>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
};

export default SingleGamePage;

这是上下文

import { useContext, useReducer, createContext, useEffect } from 'react';
import reducer from './reducer';
const AppContext = createContext();

const initialState = {
  loading: true,
  games: [],
  singleGame: {},
  current: '',
  currentGame: '',
};
const AppProvider = ({ children }) => {
  const fetchGames = async () => {
    const res = await fetch('/api/v1/games');
    const data = await res.json();
    dispatch({ type: 'GET_GAMES', payload: data });
    dispatch({ type: 'SET_LOADING' });
  };

  const fetchSingleGame = async (id) => {
    const res = await fetch(`/api/v1/games/${id}`);
    const data = await res.json();
    dispatch({ type: 'GET_SINGLE_GAME', payload: data });
    dispatch({ type: 'SET_LOADING' });
  };
  const updateTitle = () => {
    document.title = 'Games';
    dispatch({ type: 'SET_CURRENT', payload: document.title.toLowerCase() });
  };

  const currentGame = () => {
    document.title = `${state.currentGame}`;
    dispatch({ type: 'CURRENT_GAME', payload: state.singleGame.name });
  };
  useEffect(() => {
    fetchGames();
  }, []);
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <AppContext.Provider
      value={{
        ...state,
        fetchGames,
        fetchSingleGame,
        updateTitle,
        currentGame,
      }}
    >
      {children}
    </AppContext.Provider>
  );
};
export const useGlobalContext = () => {
  return useContext(AppContext);
};

export { AppContext, AppProvider };

减速器

const reducer = (state, action) => {
  switch (action.type) {
    case 'GET_GAMES':
      return {
        ...state,
        games: action.payload,
      };
    case 'SET_LOADING':
      return {
        ...state,
        loading: false,
      };

    case 'GET_SINGLE_GAME':
      return {
        ...state,
        singleGame: action.payload,
      };
    case 'SET_CURRENT':
      return {
        ...state,
        current: action.payload,
      };
    case 'CURRENT_GAME':
      return {
        ...state,
        current: action.payload,
      };
    default:
      return state;
  }
};
export default reducer;

【问题讨论】:

标签: javascript node.js reactjs api express


【解决方案1】:

尝试使用条件渲染来防止从 API 加载数组时出错:

{platforms ? platforms.map((pla) => {
    return <span className='text-light'>{pla}</span>;
  }) : 'Loading platforms...'}

【讨论】:

  • 谢谢,我会解决的!
猜你喜欢
  • 2022-01-01
  • 1970-01-01
  • 2021-03-21
  • 2019-04-17
  • 2018-02-12
  • 2021-06-11
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多