我的图像路径正在React中更改。

huangapple go评论134阅读模式
英文:

The path of my image is being changed in React

问题

这是您要翻译的代码部分:

import React, { useEffect, useState } from "react";
import { Pagination, Row } from "react-bootstrap";
import { useDispatch, useSelector } from "react-redux";
import { getProductToWishlist } from "../../RTK/Slices/wishlistSlice";
import CardProductContainer from "../products/CardProductContainer";
import ProductCard from "../products/ProductCard";

const UserFavoriteProduct = () => {
  const dispatch = useDispatch();
  const [loading, setLoading] = useState(true);
  const [items, setItems] = useState([]);

  useEffect(() => {
    const get = async () => {
      setLoading(true);
      await dispatch(getProductToWishlist());
      setLoading(false);
    };
    get();
  }, []);

  const res = useSelector((state) => state.wishlistSlice.allWishList);

  useEffect(() => {
    if (loading === false) {
      if (res) {
        setItems(
          res.data.map((item) => {
            const { id, imageCover, images } = item;
            return {
              ...item,
              images: {
                [id]: {
                  cover: imageCover,
                  others: images,
                },
              },
            };
          })
        );
      }
    }
  }, [loading]);

  return (
    <div>
      <div className="admin-content-text pb-4">قائمة المفضلة</div>
      <Row className="justify-content-start">
        {items.length <= 0 ? (
          <h6>لا يوجد منتجات مفضله حاليا</h6>
        ) : (
          <CardProductContainer products={items} title="" btntitle="" />
        )}
      </Row>
      <Pagination />
    </div>
  );
};

export default UserFavoriteProduct;

这是您要翻译的图片路径部分:

"imageCover": "http://127.0.0.1:8000/products/products-8bad93c1-19eb-4011-9dc6-dc3f704ed83c-1685630224582-cover.jpeg",
"images": [
  "http://127.0.0.1:8000/products/products-34218803-805d-4eb4-98c8-ada648f98fa8-1685630224597-1.jpeg"
],

但实际上它看起来像这样:

"imageCover": "products-33d97001-a069-492a-bd36-de7d102a92d0-1683282946006-cover.jpeg",
"images": [
  "products-fe7577fa-2c26-42cb-a46b-9666169c432a-1683282946231-2.jpeg",
  "products-4f4c53e1-9bc4-4433-bec7-61d37f18e3f7-1683282946230-1.jpeg"
],

在没有"http://127.0.0.1:8000"的情况下,您可以尝试以下方法来修复它:

  1. 在您的代码中找到所有涉及图像路径的地方,然后将路径更改为包括"http://127.0.0.1:8000"。例如:

    "imageCover": "products-33d97001-a069-492a-bd36-de7d102a92d0-1683282946006-cover.jpeg" 更改为 "imageCover": "http://127.0.0.1:8000/products-33d97001-a069-492a-bd36-de7d102a92d0-1683282946006-cover.jpeg"

    "images": ["products-fe7577fa-2c26-42cb-a46b-9666169c432a-1683282946231-2.jpeg", "products-4f4c53e1-9bc4-4433-bec7-61d37f18e3f7-1683282946230-1.jpeg"] 更改为 "images": ["http://127.0.0.1:8000/products-fe7577fa-2c26-42cb-a46b-9666169c432a-1683282946231-2.jpeg", "http://127.0.0.1:8000/products-4f4c53e1-9bc4-4433-bec7-61d37f18e3f7-1683282946230-1.jpeg"]

  2. 如果您的应用是从本地服务器获取这些图像,确保本地服务器正常运行,并且路径与实际图像位置相匹配。

请注意,如果您的应用部署到不同的环境中,可能需要动态地构建图像路径,而不是硬编码它们,以适应不同的部署环境。

英文:

Here is the code I use to get the favorite products of the user

import React, { useEffect, useState } from &quot;react&quot;;
import { Pagination, Row } from &quot;react-bootstrap&quot;;
import { useDispatch, useSelector } from &quot;react-redux&quot;;
import { getProductToWishlist } from &quot;../../RTK/Slices/wishlistSlice&quot;;
import CardProductCountainer from &quot;../products/CardProductCountainer&quot;;
import ProductCard from &quot;../products/ProductCard&quot;;
const UserFavoriteProduct = () =&gt; {
const dispatch = useDispatch();
const [loading, setLoading] = useState(true);
const [items, setItems] = useState([]);
useEffect(() =&gt; {
const get = async () =&gt; {
setLoading(true);
await dispatch(getProductToWishlist());
setLoading(false);
};
get();
}, []);
const res = useSelector((state) =&gt; state.wishlistSlice.allWishList);
useEffect(() =&gt; {
if (loading === false) {
if (res) {
setItems(
res.data.map((item) =&gt; {
const { id, imageCover, images } = item;
return {
...item,
images: {
[id]: {
cover: imageCover,
others: images,
},
},
};
})
);
}
}
}, [loading]);
return (
&lt;div&gt;
&lt;div className=&quot;admin-content-text pb-4&quot;&gt;قائمة المفضلة&lt;/div&gt;
&lt;Row className=&quot;justify-content-start&quot;&gt;
{items.length &lt;= 0 ? (
&lt;h6&gt;لا يوجد منتجات مفضله حاليا&lt;/h6&gt;
) : (
&lt;CardProductCountainer products={items} title=&quot;&quot; btntitle=&quot;&quot; /&gt;
)}
&lt;/Row&gt;
&lt;Pagination /&gt;
&lt;/div&gt;
);
};
export default UserFavoriteProduct;

The path of img is supposed to look like this:

&quot;imageCover&quot;: &quot;http://127.0.0.1:8000/products/products-8bad93c1-19eb-4011-9dc6-dc3f704ed83c-1685630224582-cover.jpeg&quot;,
&quot;images&quot;: [
&quot;http://127.0.0.1:8000/products/products-34218803-805d-4eb4-98c8-ada648f98fa8-1685630224597-1.jpeg&quot;
],

But instead it looks like this:

"imageCover": "products-33d97001-a069-492a-bd36-de7d102a92d0-1683282946006-cover.jpeg",
"images": [
"products-fe7577fa-2c26-42cb-a46b-9666169c432a-1683282946231-2.jpeg",
"products-4f4c53e1-9bc4-4433-bec7-61d37f18e3f7-1683282946230-1.jpeg"
],

Without http://127.0.0.1:8000,Wwhat can I do to fix this?

Here is the CardProductCountainer component:

import React, { useEffect, useState } from &quot;react&quot;;
import { Container, Row } from &quot;react-bootstrap&quot;;
import { useDispatch, useSelector } from &quot;react-redux&quot;;
import { getProductToWishlist } from &quot;../../RTK/Slices/wishlistSlice&quot;;
import SubTitle from &quot;../utilitys/SubTitle&quot;;
import ProductCard from &quot;./ProductCard&quot;;
const CardProductCountainer = ({ title, btntitle, pathText, products }) =&gt; {
const dispatch = useDispatch();
const [loading, setLoading] = useState(true);
const [favProd, setFavProd] = useState([]);
const res = useSelector((state) =&gt; state.wishlistSlice.allWishList);
useEffect(() =&gt; {
const get = async () =&gt; {
setLoading(true);
await dispatch(getProductToWishlist());
setLoading(false);
};
get();
}, []);
useEffect(() =&gt; {
if (loading === false) {
if (res.data.length &gt;= 1) {
console.log(res);
setFavProd(res.data.map((item) =&gt; item._id));
} else setFavProd([]);
}
}, [loading]);
return (
&lt;Container&gt;
{products ? (
&lt;SubTitle title={title} btntitle={btntitle} pathText={pathText} /&gt;
) : null}
&lt;Row className=&quot;my-2 d-flex justify-content-between&quot;&gt;
{products
? products.map((item, index) =&gt; (
&lt;ProductCard favProd={favProd} key={index} item={item} /&gt;
))
: null}
&lt;/Row&gt;
&lt;/Container&gt;
);
};
export default CardProductCountainer;

And here is the ProductCard component:

import React, { useEffect, useState } from &quot;react&quot;;
import { Card, Col } from &quot;react-bootstrap&quot;;
import prod1 from &quot;../../images/prod1.png&quot;;
import favoff from &quot;../../images/fav-off.png&quot;;
import favon from &quot;../../images/fav-on.png&quot;;
import rate from &quot;../../images/rate.png&quot;;
import { Link } from &quot;react-router-dom&quot;;
import { useDispatch, useSelector } from &quot;react-redux&quot;;
import {
addProductToWishlist,
removeProductToWishlist,
} from &quot;../../RTK/Slices/wishlistSlice&quot;;
import { ToastContainer } from &quot;react-toastify&quot;;
import notify from &quot;../../customHook/useNotification&quot;;
const ProductCard = ({ item, favProd }) =&gt; {
const dispatch = useDispatch();
const [favImg, setFavImg] = useState(favoff);
let Fav = favProd.some((fitem) =&gt; fitem === item._id);
const [loadingAdd, setLoadingAdd] = useState(true);
const [loadingRemove, setLoadingRemove] = useState(true);
const [isFav, setIsFav] = useState(Fav);
useEffect(() =&gt; {
setIsFav(favProd.some((fitem) =&gt; fitem === item._id));
}, [favProd]);
const handelFav = () =&gt; {
if (isFav) {
removeToWishListData();
} else {
addToWishListData();
}
};
useEffect(() =&gt; {
if (isFav === true) {
setFavImg(favon);
} else {
setFavImg(favoff);
}
}, [isFav]);
const resAdd = useSelector((state) =&gt; state.wishlistSlice.addWishlist);
const resRemove = useSelector((state) =&gt; state.wishlistSlice.removeWishlist);
const addToWishListData = async () =&gt; {
setIsFav(true);
setFavImg(favon);
setLoadingAdd(true);
await dispatch(
addProductToWishlist({
productId: item._id,
})
);
setLoadingAdd(false);
};
const removeToWishListData = async () =&gt; {
setIsFav(false);
setFavImg(favoff);
setLoadingRemove(true);
await dispatch(removeProductToWishlist(item._id));
setLoadingRemove(false);
};
useEffect(() =&gt; {
if (loadingAdd === false) {
if (resAdd &amp;&amp; resAdd.status === 200) {
notify(&quot;تمت اضافة المنتج للمفضلة بنجاح&quot;, &quot;success&quot;);
} else if (resAdd &amp;&amp; resAdd.status === 401) {
notify(&quot;انت غير مسجل&quot;, &quot;error&quot;);
}
}
}, [loadingAdd]);
useEffect(() =&gt; {
if (loadingRemove === false) {
if (resRemove &amp;&amp; resRemove.status === &quot;success&quot;) {
notify(&quot;تمت حذف المنتج من المفضلة بنجاح&quot;, &quot;warn&quot;);
} else if (resAdd &amp;&amp; resAdd.status === 401) {
notify(&quot;انت غير مسجل&quot;, &quot;error&quot;);
}
}
}, [loadingRemove]);
return (
&lt;Col xs=&quot;6&quot; sm=&quot;6&quot; md=&quot;4&quot; lg=&quot;3&quot; className=&quot;d-flex&quot;&gt;
&lt;Card
className=&quot;my-2&quot;
style={{
width: &quot;100%&quot;,
height: &quot;345px&quot;,
borderRadius: &quot;8px&quot;,
border: &quot;none&quot;,
backgroundColor: &quot;#FFFFFF&quot;,
boxShadow: &quot;0 2px 2px 0 rgba(151,151,151,0.5)&quot;,
}}
&gt;
&lt;Link to={`/products/${item._id}`} state={{ textDecoration: &quot;none&quot; }}&gt;
&lt;Card.Img
style={{ height: &quot;228px&quot;, width: &quot;100%&quot; }}
src={item.imageCover}
/&gt;
&lt;/Link&gt;
&lt;div className=&quot;d-flex justify-content-end mx-2&quot;&gt;
&lt;img
src={favImg}
onClick={handelFav}
alt=&quot;&quot;
className=&quot;text-center&quot;
style={{
height: &quot;24px&quot;,
width: &quot;26px&quot;,
cursor: &quot;pointer&quot;,
}}
/&gt;
&lt;/div&gt;
&lt;Card.Body&gt;
&lt;Card.Title&gt;
&lt;div className=&quot;card-title&quot;&gt;{item.title}&lt;/div&gt;
&lt;/Card.Title&gt;
&lt;Card.Text&gt;
&lt;div className=&quot;d-flex justify-content-between &quot;&gt;
&lt;div className=&quot;d-flex&quot;&gt;
&lt;img
className=&quot;&quot;
src={rate}
alt=&quot;&quot;
height=&quot;16px&quot;
width=&quot;16px&quot;
/&gt;
&lt;div className=&quot;card-rate mx-2&quot;&gt;{item.ratingsAverage || 0}&lt;/div&gt;
&lt;/div&gt;
&lt;div className=&quot;d-flex&quot;&gt;
&lt;div className=&quot;card-price&quot;&gt;{item.price}&lt;/div&gt;
&lt;div className=&quot;card-currency mx-1&quot;&gt;جنيه&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/Card.Text&gt;
&lt;/Card.Body&gt;
&lt;/Card&gt;
&lt;ToastContainer /&gt;
&lt;/Col&gt;
);
};
export default ProductCard;

答案1

得分: 0

嗨,你好 👋
首先欢迎来到Stack Overflow,如果你想得到好的回答,请确保提出问题得当。保持详细描述,但避免拼写错误和语法错误。

无论如何,以下是如何解决上述问题的方法。如有进一步问题,请在回答中留下评论,并按照以下步骤解决问题。

1. 声明一个包含你的站点URL的常量。

示例:

const URL = "127.0.0.1:8000";

2. 在使用图像源之前附加URL。

示例:

<Card.Img
 style={{ height: "228px", width: "100%" }}
 src={URL + item.imageCover}
 />

希望这有所帮助。如果有帮助,请点赞。请确保通过此链接查看如何提出更好的问题。

谢谢 ☺️

PS. 编辑
对于那些不确定上述问题的人,问题现在已经解决,原因是从服务器获取的数据导致的。无论如何,此答案中的解决方法同样有效。

英文:

> Hi, there 👋
> First of all welcome to stack overflow, if you want to get good
> response here make sure to make your question good. Keep it detailed
> as above but avoid typos and check for grammatical errors.

Anyways here is how you can solve the above problem. for further questions comment on the answer. And follow the steps to solve the problem.

1. Declear a constant holding your site url.

Example:

const URL = &quot;127.0.0.1:8000&quot;;

2. Append the URL before using the image source.

Example:

&lt;Card.Img
style={{ height: &quot;228px&quot;, width: &quot;100%&quot; }}
src={ URL + item.imageCover }
/&gt;

I hope this helps. If so give it a upvote. And make sure to Improve your question look through this link to see how you can ask better questions.

Thank you ☺️

PS. Edit
Those who are unsure about the above problem the problem is now solved and was caused by the data that was coming out of the server. Anyways the solution in this answer also works equally as well.

huangapple
  • 本文由 发表于 2023年6月8日 02:28:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426140.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定