【发布时间】:2020-01-04 10:51:23
【问题描述】:
编辑:Noob 在这里提供帮助。
我已经检查了很多类似的问题,但没有一个是相同的。
React 正在从 express 接收一个对象数组。循环,获取每个对象图像链接并将其添加到源中。
这是原始代码
{this.state.currentTemplates.map((items, pos) => {
return (
<div className={`template `}>
<img src={require(`${items.link}1.jpg`)} />
<p>{items.name}</p>
<div className="buy">buy</div>
</div>
如果存在这样的图像,require 会找到它并且它会工作。
但是如果我向另一个函数发送请求以首先检查图像是否存在,例如尝试捕获。
<div className={`template `}>
//sending url to another function. Also I can put the function outside of class and just call without 'this' and it does not make any difference.
<img src={this.checkUrl(`${items.link}1.jpg`)} />
<p>{items.name}</p>
<div className="buy">buy</div>
例如:
checkUrl(url) {
console.log(url); // receive right url '../products/templates/a.jpg'
try {
// try will require the right url but module cannot found it and it goes to catch. Now I can also put it in a variable var a= require(url) and it does not make a difference
require(url);
console.log("it works "); // it never gets to here.
return url; // this may not work once returned but it does not get to here.
}catch(e) {
//react jump to catch with "cannot find module '../products/templates/a.jpg'"
console.log(e);
}
}
我得到错误:要求找不到模块'../products/templates/1.jpg'
有趣的事情。如果我使用 templates.jsx 文件在组件文件夹中添加产品文件夹。它有效。
这也不是语法错误,我可能在此处复制了问题。
回顾:如果我直接从 src jsx 调用 require(url),它会找到图像。
如果我将 url 传递给另一个函数来尝试捕获。控制台记录正确的 url 但要求 throw 找不到模块。
这是一个反应限制吗?有解决办法吗?我是不是以错误的方式接近这个你?
【问题讨论】:
-
尝试而不需要为什么使用需要它应该可以在不需要这种形状的情况下工作
-
我试过了,这就是我得到的。图片根本不显示,但在检查中,我看到了正确的网址。 '' 但在网络选项卡中。 1.jpg 有这个错误信息。 “无法获取 /products/moveItFitness/1.jpg”。我想我必须将图像放在同一个文件夹中。它似乎无法返回 2 步。