简体   繁体   English

将库导入 Next.js 组件问题

[英]Importing Library into Next.js Component Issue

I am a little bit confused on my situation.我对自己的情况有点困惑。 For some odd reason, I am not able to import literally anything into my Nav component.出于某种奇怪的原因,我无法将任何内容导入到我的导航组件中。 However, I am able to import freely in my other components without any issues.但是,我可以毫无问题地在我的其他组件中自由导入。

import { useState, useEffect } from "react";
import styled from "styled-components";
import Link from "next/link";


const Nav = () => {
  
  const [isAuth, setIsAuth] = useState(false);
  const [user, setUser] = useState(null);

  const getUser = async () => {
    const res = await fetch("/api/me");
    const json = await res.json();
    setUser(json);
  };

  useEffect(() => {
    if (user === null || user.message === "FAILED AUTH") {
      setIsAuth(false);
    } else {
      setIsAuth(true);
    }
  }, [user]);

  useEffect(() => {
    getUser();
  }, []);

  const logout = () => {
  
  };

  return (
    <NavWrapper>
      <Home href="/">
        <StyledE>
          E<StyledBlog>BLOG</StyledBlog>
        </StyledE>
      </Home>
      
      <NavLinkWrapper>
        {isAuth ? (
          <LoggedIn>
            <Username>{user.username}</Username>
            <LogoutButton href="/account/login">
              <Logout onClick={logout}>Log Out</Logout>
            </LogoutButton>
          </LoggedIn>
        ) : (
          <LoggedOut>
            <LoginButton href="/account/login">
              <LogIn>Log In</LogIn>
            </LoginButton>
            <SignUpButton href="/account/signup">
              <SignUp>Sign Up</SignUp>
            </SignUpButton>
          </LoggedOut>
        )}
      </NavLinkWrapper>
    </NavWrapper>
  );
};
export default Nav;

This is the error I get when I try to import Cookies from "js-cookie"这是我尝试import Cookies from "js-cookie"时遇到的错误

error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

My other components import everything just fine....我的其他组件导入一切都很好....


import styled from "styled-components";
import { useState } from "react";
import Cookies from "js-cookie";


const LoginForm = () => {
  const contentType = "application/json";
  const [loginValue, setLoginValues] = useState({
    username: "",
    password: "",
  });

  const handleLoginChange = (e) => {
    const { name, value } = e.target;
    setLoginValues((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  const handleLoginSubmit = (e) => {
    e.preventDefault();
    fetch("/api/auth", {
      method: "POST",
      headers: {
        "Content-Type": contentType,
      },
      body: JSON.stringify(loginValue),
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        if (data && data.error) {
          console.log("FAILED LOGIN");
        }
        if (data && data.token) {
          console.log("Success");
          Cookies.set("token", data.token, { expires: 1 });
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <FormWrapper>
      <Form method="POST">
        <Input
          value={loginValue.username}
          type="text"
          name="username"
          placeholder="Username"
          onChange={(e) => handleLoginChange(e)}
        />
        <Input
          value={loginValue.password}
          type="password"
          name="password"
          placeholder="Password"
          onChange={(e) => handleLoginChange(e)}
        />
        <LoginButton type="button" onClick={handleLoginSubmit}>
          Login
        </LoginButton>
      </Form>
    </FormWrapper>
  );
};
export default LoginForm;

It does not give me such error....它没有给我这样的错误....

Please, does anyone know what the issue is?请问有谁知道是什么问题? I have tried everything.我已经尝试了一切。 Googled all day.谷歌了一整天。 But it keeps giving me the same error.但它一直给我同样的错误。 And not just the js-cookie library, I literally can not import anything else into this Nav component.不仅是 js-cookie 库,我实际上无法将任何其他内容导入到这个 Nav 组件中。 Not even other Components...甚至没有其他组件...

I think I solved it.我想我解决了。 For some reason, this specific component requires you to import this way:出于某种原因,此特定组件要求您以这种方式导入:

const cookies = require("js-cookie")

I am a little bit confused on why.... My other components did not need to do this...我对为什么有点困惑......我的其他组件不需要这样做......

Can someone explain or direct me to why it is like this?有人可以解释或指导我为什么会这样吗?

Also, my other form Components are imported into pages.另外,我的其他表单组件被导入到页面中。

However, Nav component is imported into a Layout component, which is then wrapped over my _app.js function但是,Nav 组件被导入到 Layout 组件中,然后将其包裹在我的 _app.js 函数中

const MyApp = ({ Component, pageProps }) => {
  
  return (
    <Layout>
      <Head>
        <title>My Blog</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <Component {...pageProps} />
    </Layout>
  );
};

Any direction would be helpful.任何方向都会有所帮助。 Thank you!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM