繁体   English   中英

未找到模块:无法在 React js 中解析“moduleName”

[英]Module not found: can't resolve 'moduleName' in react js

在从官方文档页面学习 react JS 时,到目前为止一切正常,现在当我尝试从另一个页面中的另一个页面导出一个方法时,如下所示(每个片段顶部的文件名)

源代码/Greeting.js

function UserGreeting() {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting() {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
    const isLoggedIn = props.isLoggedin;
    if(isLoggedIn) {
        return <UserGreeting />;
    } else {
        return <GuestGreeting />;
    }
}

export default Greeting;

源代码/登录控件.js

import React from 'react';

import Greeting from 'Greeting';

function LoginButton(props) {
    return <button onClick={props.onClick}>Login</button>;
}

function LogoutButton(props) {
    return <button onClick={props.onClick}>Logout</button>;
}

class LoginControl extends React.Component {


  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false})
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button = null;
    if(isLoggedIn) {
        button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
        button = <LoginButton onClick={this.handleLoginClick} />;
    }
    return (
      <div>
          <Greeting isLoggedIn={isLoggedIn} />
          {button}
      </div>
    );
  }
}

导出默认登录控件;

源代码/索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import LoginControl from './LoginControl';


 ReactDOM.render(
    <LoginControl />,
    document.getElementById('login')
);


ReactDOM.render(<App />, document.getElementById('root'));

公共/index.html

<body>
    <div id="root"></div>
    <div id="login"></div>
</body>

但它在浏览器中给出了以下错误?

./src/LoginControl.js 未找到模块:无法解析“/opt/rqt/src”中的“Greeting”

为什么我收到这个错误?

我需要在 Greeting.js 中创建一个类而不是直接导出函数吗?

您收到该错误是因为您不正确地导入了模块。 如果您这样做:

import Greeting from 'Greeting';

您的编译器将在node_modules (可能还有其他目录,具体取决于您的配置)中查找文件。


由于它位于同一目录中,因此必须将其导入为:

import Greeting from './Greeting';

基本上./表示该文件存在于当前工作目录中。

另一种可能的解决方案

FWIW 当我在脚本中的多行中使用不同的导入语法方法从单个库导入时遇到了这个问题。

为什么这会发生在我身上?

出现这个问题是因为我会像这样手动import { Stuff, Things } from 'some-library'import { Stuff, Things } from 'some-library' ,然后在我编码时,VS Code 会自动引入新的导入。 所以,我最终会在我的脚本中得到这个:

import { Stuff, Things } from 'some-library'
...
import Code from 'some-library/Code'

出于某种原因,当发生这种情况时,会抛出此错误。

技术栈

  • Next.js
  • 材质界面

出现此错误的主要原因是,您尚未正确验证相对路径,或者您尚未提供导入项目的扩展名。

暂无
暂无

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

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