[英]Why can't React find this file?
我正在使用 MERN(MongDb Express React Node) 构建我的第一个 web 应用程序,但我在理解为什么 React 似乎找不到我要导入的文件时遇到了问题。
我尝试了在导入中更改文件路径的每个不同版本,从所有尝试中添加/删除.js
,三次检查没有拼写错误/大写问题,并进行npm update
只是为了尝试不同的东西。 我在这里碰壁了。
该应用程序当前所做的只是使用setState
更改按钮中的文本。 稍后我将根据数据库内容做更多的事情,但我只是想知道如何首先在前端显示来自后端的信息。
我得到的主要错误是:
[错误:ENOENT:没有这样的文件或目录,stat '/initrd.img'] { errno:-2,代码:'ENOENT',系统调用:'stat',路径:'/initrd.img'}
./src/App.js 未找到模块:您试图导入项目 src/ 目录之外的 /components/number.js。 不支持 src/ 之外的相对导入。
我认为这可能是我尝试导入/导出东西的问题吗? 这是我迄今为止用来破解我所拥有的资源的资源:
应用程序.js
import logo from './logo.svg';
import './App.css';
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import Numbers from './components/number.js';
class App extends Component {
constructor(props) {
super(props)
this.state = {
buttonText: "button1"
}
this.changeWord = this.changeWord.bind(this);
}
changeWord() {
if (this.state.buttonText === "button2") {
this.setState({
buttonText: "button1"
})
}
else {
this.setState({
buttonText: "button2"
})
}
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<Numbers />
<button className="test-button" onClick={this.changeWord}>{this.state.buttonText}</button>
</header>
</div>
);
}
}
export default App;
数字.js
import React, { Component } from "react";
import axios from "axios";
import { response } from "express";
export default class Numbers extends Component {
constructor(props) {
super(props);
this.state = {
numbers: []
};
}
componentDidMount() {
axios
.get("http://localhost:3000/record/")
.then((response) => {
this.setState({
numbers: response.data
});
console.log(this.state.numbers);
})
.catch(function(err) {
console.log(err);
});
}
render() {
return (
<div>
<h3>Numbers</h3>
<table>
<thead>
<tr>
<th>Number</th>
</tr>
</thead>
<tbody>{this.numbers()}</tbody>
</table>
</div>
);
}
}
编辑:
以 src 作为工作目录的项目树
├── App.css
├── App.js
├── App.test.js
├── components
│ └── number.js
├── index.css
├── index.js
├── logo.svg
├── reportWebVitals.js
└── setupTests.js
我认为问题在于您的组件 js 文件“number.js”的命名。 应改为“Number.js”(大写字母 N)
根据反应文档,
当元素类型以小写字母开头时,它指代内置组件,如 or 并导致传递给 React.createElement 的字符串 'div' 或 'span'。 以大写字母开头的类型,如编译为 React.createElement(Foo) 并对应于 JavaScript 文件中定义或导入的组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.