gpt4 book ai didi

javascript - 获取请求 axios React js useEffect 不起作用(找不到模块 './undefined' )

转载 作者:行者123 更新时间:2023-12-02 21:05:54 25 4
gpt4 key购买 nike

我正在构建一个模拟社交网络,但我陷入了一个我无法完全理解的问题。以下是我正在实现的不同结果和代码。

错误:

Error: Cannot find module './undefined'
▼ 2 stack frames were expanded.
webpackContextResolve
C:/Users/sanjs/desktop/demo-react/src/assets sync /^/.*$:18
webpackContext
C:/Users/sanjs/desktop/demo-react/src/assets sync /^/.*$:13
▲ 2 stack frames were expanded.
Profile
C:/Users/sanjs/desktop/demo-react/src/components/ProfileSection/Profile.js:16
13 | <div className='profile--image'>
14 | <Image
15 | alt={`imagen de ${profile.title}`}
> 16 | imgSrc={require(`../../assets/${profile.imagen}`)}
| ^ 17 | />
18 |
19 | </div>

配置文件组件:接收配置文件属性,就像要显示的对象一样

                     <div className='content--content'>

<div className='profile--image'>
<Image
alt={`imagen de ${profile.title}`}
imgSrc={require(`../../assets/${profile.imagen}`)} <--

//if I delete this above line of code the error does not appear
//the data is displayed normally except the image of course

/>

</div>

...

</div>

然后在 ProfileDetail 中查询数据并实现 Profile 组件:

 const ProfileDetail = ({
match
}) => {

const [ data, setData ] = useState({})

useEffect(() => {
async function getProfiles(){
const result = await axios(
`http://localhost:8001/api/profiles/${match.params.id}`,
);
setData(result.data);

}
getProfiles()
}, [match]);

console.log(data) // --> this logs an empty object {} the initial state.
return (
<div className='profileDetail--container'>

<Profile
profile={data}
/>

...
</div>
)
}

express 服务器通过 id 获取配置文件和配置文件:

const path = require('path');

const express = require('express');

const cors = require('cors');

const data = require('./data/profiles.json')

const app = express();

app.use(cors());

const port = 8001;

app.get('/api/profiles', (req, res) => {
res.sendFile(path.join(__dirname, 'data', 'profiles.json'));
});

app.get('/api/profiles/:id', function (req, res) {
const profileId = Number(req.params.id)
const getProfile = data.profiles.find((profile)=>profile.id === profileId)

if(!getProfile){
res.status(500).send('some error message')
}else{
res.json(getProfile)
}
})

app.listen(port, () => {
console.log(`[profiles] API listening on port localhost:${port}/api/profiles.`);
});

在浏览器中,这似乎工作得很好... http//localhost:8001/api/profiles 和 http//localhost:8001/api/profiles/1 带来了数据,但有一些特殊性。使用第一个 URL,数据将在浏览器中呈现,如下所示:

{
"profiles":[
{
"id":1,
"name":"Rick",
"lastName":"Sanchez",
"tweets":["tweet1","tweet2"]
},
{
"id":2,
"name":"Morty",
"lastName":"Smith",
"tweets":["tweet1","tweet2"]
},
etc...
]
}

第二个像这样:

{id:1,name:"Rick",lastName:"Sanchez"} 

我可以显示删除下面一行的组件,但没有个人资料图片

imgSrc={require(`../../assets/${profile.imagen}`)}

首先,日志是一个 {},然后按应有的方式打印两次配置文件详细数据...否则打印错误消息...

我希望我已经清楚地解释了这个问题,如果有人知道发生了什么,请告诉我,提前致谢。

最佳答案

如果您使用 CRA refer to how to add an image,则运行时不存在这样的路径 ../../assets/${profile.imagen}

import React from 'react';
import logo from './logo.png'; // Tell webpack this JS file uses this image
console.log(logo); // /logo.84287d09.png
function Header() {
// Import result is the URL of your image
return <img src={logo} alt="Logo" />;
}
export default Header;

如果您想动态执行此操作,请使用public(静态)文件夹或导入相关图像并使用字典,例如:

import logo1 from "./logo.png";
import logo2 from "./logo2.png";

const LOGO = {
logo1: logo1,
logo2: logo2,
};

function Header({ logoId }) {
return <img src={LOGO[logoId]} alt="Logo" />;
}

关于javascript - 获取请求 axios React js useEffect 不起作用(找不到模块 './undefined' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61229145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com