不在React中定义数组的长度

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

not defining array's length in reactjs

问题

I'm using fetch to get the product as an object and while setting it to my state I'm adding a new key comments: [] to the object. If I console.log(product.comments) it's returning an empty array, which is correct. But when I console.log(product.comments.length), it says "can't access property 'length', product.comments is undefined."

useEffect(() => {
    setLoading(true);
    fetch(`https://fakestoreapi.com/products/${id}`)
        .then((res) => res.json())
        .then((data) => {
            setProduct({ ...data, comments: [] });
            setLoading(false);
        })
        .catch((err) => console.error(err));
}, [id]);

What did I do wrong? How can I get the length of comments so that I can map it?

This is what I want to do:

{product.comments.length ? (
    comments.map((comment) => {
        return (
            <li>
                <div className="testimonial">
                    <p className="quote">{comment.comment}</p>
                </div>
            </li>
        );
    })
) : (
    <h2>Be the first to comment</h2>
)}

I also tried logging product.comments.length to the console but got the same error.

英文:

I'm using fetch to get the product as an object and while setting it to my state I'm adding new key comments: [] to the object. If I console.log(product.comments) it's returning empty array which's correct but when I console.log(product.comments.length) it says can&#39;t access property &quot;length&quot;, product.comments is undefined

useEffect(() =&gt; {
	
	setLoading(true)
	fetch(`https://fakestoreapi.com/products/${id}`)
		.then((res) =&gt; res.json())
		.then((data) =&gt; {
			setProduct({ ...data, comments: [] })
			setLoading(false)
		})
		.catch((err) =&gt; console.error(err))
}, [id])

what did I do wrong, how to get the length of comments so that I can map it?
this is what I wanna do

`{product.comments.length ? (
  comments.map((comment) =&gt; {
   return (
    &lt;li&gt;
     &lt;div className=&quot;testimonial&quot;&gt;
      &lt;p className=&quot;quote&quot;&gt;{comment.comment}&lt;/p&gt;
     &lt;/div&gt;
    &lt;/li&gt;
   )
 })
 ) : (
    &lt;h2&gt;Be first to comment&lt;/h2&gt;
 )}`

I also tried logging product.comments.length to console but got the same error

答案1

得分: 0

问题与渲染周期有关。可以尽早从您的组件中返回,例如:

// data, isLoading, error = fetchData()

if (isLoading) { return <div>加载中...</div> }
if (error) { return <div>错误</div> }

return (<div>您的组件内容</div>)

或者您可以在访问length属性之前检查属性是否存在,可以使用可选链操作符。

{product?.comments.length ? (product.comments.map( ... )) : (<h2>首先评论一下</h2>)}
英文:

The issue is related to render cycles. Either early return from your component e.g.

// data, isLoading, error = fetchData()

if (isLoading) { return &lt;div&gt;Loading &lt;/div&gt;
if (error) { return &lt;div&gt;Error&lt;/div&gt; }

return ( &lt;div&gt;Your component body&lt;/div&gt;)

Or you could check if the property exists before accessing the length property using the optional chaining operator.

{product?.comments.length ? (product.comments.map(  )) : (&lt;h2&gt;Be first to comment&lt;/h2&gt;)}

答案2

得分: 0

这是因为在访问 comments 之前,你试图在产品上设置它之前,应该先检查 product 是否为空或已设置,然后才能访问它的任何属性。

if (product) {
  return {
    product.comments.length ? (comments.map((comment) => {
      return (
        <li>
          <div className="testimonial">
            <p className="quote">{comment.comment}</p>
          </div>
        </li>
      );
    })) : (
      <h2>Be first to comment</h2>
    )
  };
} else {
  return <p>Product loading</p>;
}
英文:

That is because you are trying to access comments even before it's set on the product you should just check if product is not empty or set before you can access any property on it.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

if(product) {
    return {product.comments.length ? (comments.map((comment) =&gt; {
       return (&lt;li&gt;
            &lt;div className=&quot;testimonial&quot;&gt;
                &lt;p className=&quot;quote&quot;&gt;{comment.comment}&lt;/p&gt;
            &lt;/div&gt;
        &lt;/li&gt;);
    })) : (
      &lt;h2&gt;Be first to comment&lt;/h2&gt;
   )};
} else {
    return &lt;p&gt;Product loading&lt;/p&gt;
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月4日 02:51:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630849.html
匿名

发表评论

匿名网友

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

确定