未捕获的引用错误:无法在初始化之前访问'__WEBPACK_DEFAULT_EXPORT__'[React]

2skhul33  于 2023-10-19  发布在  Webpack
关注(0)|答案(1)|浏览(264)

我得到这个错误

Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization

我已经检查了循环依赖,但找不到。我给你下面几乎所有的代码。告诉我是怎么回事,因为在本地主机上没有任何东西被渲染,它只是一个白色屏幕。

App.js

import React from "react";
import { useEffect } from "react";
import "./App.css";
import HomeScreen from "./pages/HomeScreen";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Login from "./pages/Login";
import { auth } from "./firebase";
import { useDispatch, useSelector } from "react-redux";
import { login, logout, selectUser } from "./features/userSlice";
import Profile from "./pages/Profile";

export default function App() {
  const user = useSelector(selectUser);
  const dispatch = useDispatch();

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((userAuth) => {
      if (userAuth) {
        //logged in
        console.log(userAuth);
        dispatch(
          login({
            uid: userAuth.uid,
            email: userAuth.email,
          })
        );
      } else {
        //logged out
        dispatch(logout());
      }
    });

    return unsubscribe;
  }, []);

  return (
    <div className='app'>
      <Router>
        {!user ? (
          <Login />
        ) : (
          <Routes>
            <Route path='/profile'>
              <Profile />
            </Route>
            <Route exact path='/'>
              <HomeScreen />
            </Route>
          </Routes>
        )}
      </Router>
    </div>
  );
}

axios.js

import axios from "axios";

const instance = axios.create({
  baseURL: "https://api.themoviedb.org/3",
});

export default instance;

firebase.js

import firebase from "./firebase";

const firebaseConfig = {
  apiKey: "0",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
};

const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();

export { auth };
export default db;

HomeScreen.js

import React from "react";
import Banner from "../Banner";
import Navbar from "../Navbar";
import requests from "../Requests";
import Row from "../Row";
import "./HomeScreen.css";

export default function HomeScreen() {
  return (
    <div className='homeScreen'>
      <Navbar />
      <Banner />
      <Row
        title='Netflix Originals'
        fetchUrl={requests.fetchNetflixOriginals}
        isLargeRow
      />
      <Row title='Top Rated' fetchUrl={requests.fetchTopRated} />
      <Row title='Trending Now' fetchUrl={requests.fetchTrending} />
      <Row title='Action Movies' fetchUrl={requests.fetchActionMovies} />
      <Row title='Comedy Movies' fetchUrl={requests.fetchComedyMovies} />
      <Row title='Documentries' fetchUrl={requests.fetchDocumantaries} />
      <Row title='Horror Movies' fetchUrl={requests.fetchHorrorMovies} />
      <Row title='Romance Movies' fetchUrl={requests.fetchRomanceMovies} />
    </div>
  );
}

Login.js

import React from "react";
import { useState } from "react";
import Signup from "./Signup";
import "./Login.css";

export default function Login() {
  const [signIn, setSignIn] = useState(false);
  return (
    <div className='login'>
      <div className='login_bg'>
        <img
          className='login_logo'
          src='https://assets.stickpng.com/images/580b57fcd9996e24bc43c529.png'
          alt='netflix logo'
        />
        <button onClick={() => setSignIn(true)} className='login_button'>
          Sign In
        </button>

        <div className='login_gradient' />
      </div>
      <div className='login_body'>
        {signIn ? (
          <Signup />
        ) : (
          <>
            <h1>Unlimited movies, TV shows and more.</h1>
            <h2>Watch anywhere. Cancel anytime.</h2>
            <h3>
              Ready to watch? Enter your email to create or restart your
              membership.
            </h3>

            <div className='login_input'>
              <form>
                <input type='email' placeholder='EmailAddress' />
                <button
                  onClick={() => setSignIn(true)}
                  className='login_getStarted'
                >
                  Get Started
                </button>
              </form>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

Signup.js

import React from "react";
import { useRef } from "react";
import { auth } from "../firebase";
import "./Signup.css";

export default function Signup() {
  const emailRef = useRef(null);
  const passwordRef = useRef(null);

  const register = (e) => {
    e.preventDefault();

    auth
      .createUserWithEmailAndPassword(
        emailRef.current.value,
        passwordRef.current.value
      )
      .then((authUser) => {
        console.log(authUser);
      })
      .catch((error) => {
        alert(error.message);
      });
  };

  const signIn = (e) => {
    e.preventDefault();

    auth
      .signInWithEmailAndPassword(
        emailRef.current.value,
        passwordRef.current.value
      )
      .then((authUser) => {
        console.log(authUser);
      })
      .catch((error) => {
        alert(error.message);
      });
  };

  return (
    <div className='signup'>
      <form>
        <h1>Sign In</h1>
        <input ref={emailRef} placeholder='Email' type='email' />
        <input ref={passwordRef} placeholder='Password' type='password' />
        <button type='submit'>Sign In</button>

        <h4>
          <span className='signup_gray'>New to Netflix? </span>{" "}
          <span className='signup_link'>Sign Up now.</span>
        </h4>
      </form>
    </div>
  );
}

Banner.js

import React from "react";
import { useEffect, useState } from "react";
import axios from "axios";
import requests from "./Requests";
import "./Banner.css";

export default function Banner() {
  const [movie, setMovie] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const request = await axios.get(requests.fetchNetflixOriginals);
      setMovie(
        request.data.results[
          Math.floor(Math.random() * request.data.results.length - 1)
        ]
      );
      return request;
    }
    fetchData();
  }, []);

  console.log(movie);

  function truncate(string, n) {
    return string?.length > n ? string.substr(0, n - 1) + "..." : string;
  }
  return (
    <header
      className='banner'
      style={{
        // height: "100vh",
        backgroundSize: "cover",
        backgroundImage: `url("https://image.tmdb.org/t/p/original/${movie?.backdrop_path}")`,
        backgroundPosition: "top center",
        backgroundRepeat: "no-repeat",
      }}
    >
      <div className='banner_contents'>
        <h1 className='banner_title'>
          {movie?.title || movie?.name || movie?.original_name}
        </h1>
        <div className='banner_buttons'>
          <button className='banner_button_play'>Play</button>
          <button className='banner_button'>My List</button>
        </div>
        <h1 className='banner_description'>{truncate(movie?.overview, 150)}</h1>
      </div>

      <div className='banner--fadeBottom' />
    </header>
  );
}

Row.js

import React from "react";
import { useEffect, useState } from "react";
import axios from "axios";
import "./Row.css";

export default function Row({ title, fetchUrl, isLargeRow = false }) {
  const [movies, setMovies] = useState([]);

  const base_url = "https://image.tmdb.org/t/p/original/";

  useEffect(() => {
    async function fetchData() {
      const request = await axios.get(fetchUrl);
      setMovies(request.data.results);
      return request;
    }
    fetchData();
  }, [fetchUrl]);
  return (
    <div className='row'>
      <h2>{title}</h2>

      <div className='row_posters'>
        {movies.map(
          (movie) =>
            ((isLargeRow && movie.poster_path) ||
              (!isLargeRow && movie.backdrop_path)) && (
              <img
                className={`row_poster ${isLargeRow && "row_posterLarge"}`}
                key={movie.id}
                src={`${base_url}${
                  isLargeRow ? movie.poster_path : movie.backdrop_path
                }`}
                alt={movie.name}
              />
            )
        )}
      </div>
    </div>
  );
}

store.js

import { configureStore } from "l@reduxjs/toolkit";
import userReducer from "../features/userSlice.js";

export default configureStore({
  reducer: {
    user: userReducer,
  },
});

userSlice.js

import { createSlice } from "@reduxjs/toolkit";

export const userSlice = createSlice({
  name: "user",
  initialState: {
    user: 0,
  },
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
});

export const { login, logout } = userSlice.actions;
export const selectUser = (state) => state.user.user;
export default userSlice.reducer;

我认为这是因为axios,所以我给了所有的文件,其中包含axios在它。

fivyi3re

fivyi3re1#

此错误与循环依赖项或不正确的导入/导出用法有关,但在代码中,我没有看到任何这些错误
我唯一能想到的是firebase.js文件中的firebase导入不正确。
您正在从自身导入firebase,这可能会导致问题。
更改此选项:

import firebase from "./firebase";

对此:

import firebase from 'firebase/compat/app';
import "firebase/compat/auth";
import 'firebase/compat/firestore';

顺便说一句,请确保您的axios导入和使用是正确的-在HomeScreen.js和其他组件中导入的请求对象定义正确,并包含适当的URL。

相关问题