Rumah  >  Soal Jawab  >  teks badan

Melewati fungsi sebagai harta kepada dua komponen mengembalikan tidak ditentukan dalam komponen sasaran

rreeee

Jadi ini adalah komponen induk dan dari sini saya menyerahkan fungsi handleNewLikes sebagai prop kepada Row.

import React, { useContext, useState } from 'react';
import Main from '../components/Main';
import Row from '../components/Row';
import requests from '../requests';
import AppContext from '../lib/AuthContext';

const Home = () => {

  const [likedItems, setLikedItems] = useState([]);

  const contextValue = useContext(AppContext);
  const token = window.localStorage.getItem('trailerflix-jwt');

  const handleNewLikes = item => {
    setLikedItems(prevLikedItems => [...prevLikedItems, item]);
  };

  if (token && contextValue.user?.user) {
    return (
      <>
        <Main handleNewLikes={handleNewLikes} />
        <Row rowId='0' title={`${(token && contextValue.user?.user) ? contextValue?.user?.user.username : null}'s List`} fetchURL='/auth/get-likes'
        likedItems={likedItems} handleNewLikes={handleNewLikes} />
        <Row rowId='1' title='Top 10 Movies in the U.S. Today' fetchURL={requests.popular} />
        <Row rowId='2' title='Coming Soon' fetchURL={requests.upcoming} />
        <Row rowId='3' title='Trending Now' fetchURL={requests.trending} />
        <Row rowId='4' title='Now Playing in Theaters' fetchURL={requests.nowPlaying} />
        <Row rowId='5' title='Animation' fetchURL={requests.animation} />
        <Row rowId='6' title='Horror' fetchURL={requests.horror} />
        <Row rowId='7' title='Comedy' fetchURL={requests.comedy} />
      </>
    );
  } else {
    return (
      <>
        <Main />
        <Row rowId='1' title='Top 10 Movies in the U.S. Today' fetchURL={requests.popular} />
        <Row rowId='2' title='Coming Soon' fetchURL={requests.upcoming} />
        <Row rowId='3' title='Trending Now' fetchURL={requests.trending} />
        <Row rowId='4' title='Now Playing in Theaters' fetchURL={requests.nowPlaying} />
        <Row rowId='5' title='Animation' fetchURL={requests.animation} />
        <Row rowId='6' title='Horror' fetchURL={requests.horror} />
        <Row rowId='7' title='Comedy' fetchURL={requests.comedy} />
      </>
    );
  }

};

export default Home;

Ini ialah komponen baris tempat saya menyampaikan fungsi handleNewLikes kepada media.

import axios from 'axios';
import React, { useEffect, useState, useRef } from 'react';
import Media from './Media';
import { MdChevronLeft, MdChevronRight } from 'react-icons/md';

const Row = ({ title, fetchURL, rowId, videos, likedItems, handleNewLikes }) => {

  const [media, setMedia] = useState([]);

  useEffect(() => {
    const token = window.localStorage.getItem('trailerflix-jwt');
    if (token && fetchURL === '/auth/get-likes') {
      axios.get(fetchURL, {
        headers: {
          'Content-Type': 'application/json',
          'X-Access-Token': `${token}`
        }
      })
        .then(res => {
          const flattenedArray = res.data.map(item => item.favoritedItem);
          const newestLikesFirst = flattenedArray.reverse();
          setMedia(newestLikesFirst);
        })
        .catch(error => {
          console.error('Axios GET request failed:', error);
        });
    } else if (fetchURL !== '/auth/get-likes') {
      axios.get(fetchURL)
        .then(response => {
          setMedia(response.data.results);
        })
        .catch(error => {
          console.error('Axios GET request failed:', error);
        });
    }
  }, [fetchURL, likedItems]);

  const validMedia = [];

  for (let i = 0; i < media.length; i++) {
    if (media[i].backdrop_path !== null) {
      validMedia.push(media[i]);
    } else {
      media.splice(i, 1);
    }
  }

  const rowRef = useRef(null);
  const [isMoved, setIsMoved] = useState(false);

  const handleSlider = direction => {
    setIsMoved(true);

    if (rowRef.current) {
      const { scrollLeft, clientWidth } = rowRef.current;

      const scrollTo =
        direction === 'left' ? scrollLeft - clientWidth : scrollLeft + clientWidth;

      rowRef.current.scrollTo({ left: scrollTo, behavior: 'smooth' });
    }

  };

  return (

    <>
      <h2 className='text-white font-bold md:text-2xl p-4 mt-8 mb-3 ml-4'>{title}</h2>
      <div className='relative flex items-center group mb-10 ml-4'>

        <MdChevronLeft className={`text-white bg-transparent left-0 absolute hover:opacity-100 cursor-pointer z-10 hidden invisible lg:visible md:visible group-hover:block ${!isMoved && ' lg:invisible md:invisible'}`} size={60}
          onClick={() => handleSlider('left')}
        />
        <div id={'slider' + rowId} className='w-full h-full overflow-x-scroll whitespace-nowrap scroll-smooth relative scrollbar-hide overflow-y-hidden' ref={rowRef}>
          {validMedia.map((item, id) => {
            return <Media key={id} item={item} rowId={rowId} handleNewLikes={handleNewLikes} likedItems={likedItems}/>;
          })}
        </div>
        <MdChevronRight className='text-white bg-transparent right-0 absolute hover:opacity-100 cursor-pointer z-10 hidden invisible lg:visible md:visible group-hover:block' size={60}
          onClick={() => handleSlider('right')}
        />
      </div>
    </>
  );
};

export default Row;

Dalam media, fungsi kadangkala ditakrifkan dalam konsol dan kadangkala tidak ditentukan. Selain itu, apabila saya mengklik pada ikon hati dan fungsi handleLikes dicetuskan, fungsi handleNewLikes di dalamnya akan sentiasa muncul sebagai tidak ditentukan.

Ini yang saya nampak dalam konsol

Terima kasih atas bantuan anda, saya telah terperangkap selama beberapa hari lmao

Saya tahu saya mungkin boleh menggunakan beberapa jenis perpustakaan pengurusan negeri, tetapi itu memerlukan sedikit pemfaktoran semula, dan saya rasa ini sepatutnya berfungsi, dan saya tidak nampak mengapa akan ada sebarang masalah, melainkan saya sedang rabun jauh. < /p>

P粉818125805P粉818125805208 hari yang lalu377

membalas semua(1)saya akan balas

  • P粉762730205

    P粉7627302052024-02-27 09:48:52

    Saya menyalin kod anda dan menambahkan beberapa log untuk membantu anda melihat perkara yang sedang berlaku. Anda hanya bermula dari Home -> MainHome -> Row 0传递了handleNewLikes.

    Barisan selebihnya adalah handleNewLikes正确地为undefined kerana anda tidak melepasi fungsi ini. Lihat log ini untuk melihat apa yang saya maksudkan:

    Apabila kita mencapai fungsi Media组件时,你在调用handleLikes时尝试使用一个undefinedhandleNewLikes.

    // Media.tsx line 48
      const handleLikes = () => {
        const token = window.localStorage.getItem("trailerflix-jwt");
        if (token && contextValue?.user?.user) {
          axios
            .post("/auth/likes", item, {
              headers: {
                "Content-Type": "application/json",
                "X-Access-Token": token
              }
            })
            .then((response) => {
              console.log(handleNewLikes);
              // Undefined because not passed in to Row which passes to Media
              handleNewLikes(item); 
              setIsLiked(true);
            })
            .catch((error) => {
              console.error("Fetch failed during POST", error);
            });
        } else {
          window.alert("You need to be signed in to save a movie!");
        }
      };

    Berikut adalah beberapa log daripada Media组件中点击like按钮:

    Penyelesaian paling mudah ialah di Home中更新Row实现的参数,包括handleNewLikes:

    <Row 
      rowId='1' 
      title='Top 10 Movies in the U.S. Today' 
      fetchURL={requests.popular} 
      handleNewLikes={handleNewLikes} 
    />
    // 同样适用于row 2、3等...

    Ini ialah log mengklik butang suka selepas menghantar fungsi ke Row 1

    ^ Anda harus menggunakan beberapa jenis pengurusan negeri. Anda tidak perlu menggunakan perpustakaan untuk melakukan ini. Jika keadaan tidak begitu kompleks, anda boleh menggunakan konteks React yang serupa dengan apa yang anda lakukan dalam AuthContext.

    balas
    0
  • Batalbalas