Getting TypeError: Cannot read properties of undefined (reading 'map') when i try to fetch data

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

Getting TypeError: Cannot read properties of undefined (reading 'map') when i try to fetch data

问题

我有一个React前端,当我尝试从我的Node.js后端获取数据时,但我的API似乎没有问题。

const SingleProductPage = () => {

  const { productId } = useParams();

  const [product, setProduct] = useState({});

  useEffect(() => {
    const fetchProduct = async () => {
      const { data } = await axios.get(`/api/Product/${productId}`);
      setProduct(data);
    };
    fetchProduct();
  }, [productId]);

  if (!product) {
    return <Error errorMessage="抱歉,未找到产品!" />;
  }


  return (
        <div className="single-slider-div">
          <Splide>
            {product.src.map((src, index) => (
              <SplideSlide>
                <img key={index} src={src} alt="产品图片" />
              </SplideSlide>
            ))}
          </Splide>
        </div>
      
  );
};

export default SingleProductPage;

我尝试将一个对象设置为product的初始状态,但返回了相同的错误,我尝试测试后端路由,它运行正常。我已添加了相关部分的代码。

英文:

I have a react frontend and when i try to get data from my node js backend but my api seems to be in order

const SingleProductPage = () =&gt; {

  const { productId } = useParams();

  const [product, setProduct] = useState({});

  useEffect(() =&gt; {
    const fetchProduct = async () =&gt; {
      const { data } = await axios.get(`/api/Product/${productId}`);
      setProduct(data);
    };
    fetchProduct();
  }, [productId]);

  if (!product) {
    return &lt;Error errorMessage=&quot;Sorry, Product not found!&quot; /&gt;;
  }


  return (
        &lt;div className=&quot;single-slider-div&quot;&gt;
          &lt;Splide&gt;
            {product.src.map((src, index) =&gt; (
              &lt;SplideSlide&gt;
                &lt;img key={index} src={src} alt=&quot;product img&quot; /&gt;
              &lt;/SplideSlide&gt;
            ))}
          &lt;/Splide&gt;
        &lt;/div&gt;
      
  );
};

export default SingleProductPage;

I tried setting an object as the initial state for product but it returns the same error, i tried testing the backend route and it works fine. I have added relevant parts of the code.

答案1

得分: 1

在你的返回语句中添加对 productproduct.src 的条件检查。还要在 SplideSlide 组件上添加 key={index}

return (
    <div className="single-slider-div">
        <Splide>
            {product && product.src && product.src.map((src, index) => (
                <SplideSlide key={index}>
                    <img src={src} alt="product img" />
                </SplideSlide>
            ))}
        </Splide>
    </div>
);
英文:

Add a conditional check for product and product.src in your return statement. Also add key={index} to the SplideSlide component.

return (
    &lt;div className=&quot;single-slider-div&quot;&gt;
        &lt;Splide&gt;
            {product &amp;&amp; product.src &amp;&amp; product.src.map((src, index) =&gt; (
                &lt;SplideSlide key={index}&gt;
                    &lt;img src={src} alt=&quot;product img&quot; /&gt;
                &lt;/SplideSlide&gt;
            ))}
        &lt;/Splide&gt;
    &lt;/div&gt;
);

答案2

得分: 0

代码已翻译如下:

似乎您正尝试在组件呈现之前访问product.src因此出现了未定义的值错误您可以将代码重构如下 -

```jsx
const SingleProductPage = () => {
  const { productId } = useParams();
  const [product, setProduct] = useState({});

  useEffect(() => {
    const fetchProduct = async () => {
      try {
        const { data } = await axios.get(`/api/Product/${productId}`);
        setProduct(data);
      } catch (error) {
        //? 错误处理
        console.log(error);
      }
    };
    fetchProduct();
  }, [productId]);

  // 将if语句更改以考虑product.src
  if (!product || !product.src) {
    return <Error errorMessage="抱歉,找不到产品!" />;
  }

  return (
    <div className="single-slider-div">
      <Splide>
        {product.src.map((src, index) => (
          // 在此定义key属性
          <SplideSlide key={index}>
            <img src={src} alt="product" />
          </SplideSlide>
        ))}
      </Splide>
    </div>
  );
};

export default SingleProductPage;

此外,我还将key属性移到"SplideSlide"组件上,因为在映射数组时,按照React文档中这里提到的最佳实践,最好在最外层元素上定义key属性。


<details>
<summary>英文:</summary>

It seems like you are trying to access the product.src before the component is rendered and hence the undefined value error. You can refactor the code as follows -&gt;

const SingleProductPage = () => {
const { productId } = useParams();
const [product, setProduct] = useState({});

useEffect(() => {
const fetchProduct = async () => {
try {
const { data } = await axios.get(/api/Product/${productId});
setProduct(data);
} catch (error) {
//? Error handling
console.log(error);
}
};
fetchProduct();
}, [productId]);

// changed the if statement to factor in the product.src
if (!product || !product.src) {
return <Error errorMessage="Sorry, Product not found!" />;
}

return (
<div className="single-slider-div">
<Splide>
{product.src.map((src, index) => (

// defining key prop here
<SplideSlide key={index}>
<img src={src} alt="product" />
</SplideSlide>
))}
</Splide>
</div>
);
};

export default SingleProductPage;


In addition, I also moved the key prop up to the &quot;SplideSlide&quot; component as it is best practice to define the key prop at the outermost element when mapping over an array as mentioned [here][1] in React docs.


  [1]: https://legacy.reactjs.org/docs/lists-and-keys.html

</details>



huangapple
  • 本文由 发表于 2023年6月6日 10:38:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76411112.html
匿名

发表评论

匿名网友

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

确定