简体   繁体   English

类型错误:无法读取未定义 Reactjs 的属性“标题”

[英]TypeError: Cannot read property 'title' of undefined Reactjs

I dont know why i have this error:!我不知道为什么我有这个错误:! At first time i dont have any error and its work But when i refresh the page i have this error: TypeError: Cannot read property 'title' of undefined or TypeError: Cannot read property 'image' of undefined第一次我没有任何错误及其工作但是当我刷新页面时出现此错误: TypeError:无法读取未定义的属性“标题”TypeError:无法读取未定义的属性“图像”

import React, { useEffect , useState } from 'react';
import Content from './Content';
import NavBar from './NavBar';

    export default function BlogPost() {

    const [post, setPost] = useState([]);
    const [current, setCurrent] = useState(null)

    useEffect(() => {
       const cleanUp = fetch('http://localhost:3000/posts')
       .then( response => response.json())
       .then( post => 
           setPost(post),
           setCurrent(0)
       )
       return () => cleanUp;
    },[])

    function handleClick(index) {
        setCurrent(index)
    }
     

    return (
        <div className="wrapper d-flex align-items-stretch">
          <NavBar posts={post} handleClick={handleClick} />
          { null != current && <Content post={post[current]} />}
        </div>
    )
}

Content.jsx:内容.jsx:

export default function Content({post}) {
    return (
       <div>
          <div id="content" className="p-4 p-md-5 pt-5">
        <img src={`/assets/${post.image}`} alt={post.title} />
     <h2 className="mb-4">{post.title}</h2>
     <p>{post.body}</p>
  </div>
       </div>
    )
}

The issue is here:问题在这里:

<h2 className="mb-4">{post.title}</h2>

here post object will get data from axios call and it will take some time to fetch the data that means on initial render title will not be there.此处post object 将从 axios 调用中获取数据,并且需要一些时间来获取数据,这意味着初始渲染title将不存在。 So you have to put some check and access that key only when it is available.因此,您必须进行一些检查并仅在该密钥可用时才能访问该密钥。

Try something like:尝试类似:

<h2 className="mb-4">{post && post.title}</h2>

Or you can also try conditional rendering或者你也可以试试conditional rendering

you could do the below instead:您可以改为执行以下操作:

export default function Content({post}) {
    return post ? (
       <div>
         <div id="content" className="p-4 p-md-5 pt-5">
           <img src={`/assets/${post.image}`} alt={post.title} />
           <h2 className="mb-4">{post.title}</h2>
           <p>{post.body}</p>
         </div>
       </div>
    ) : null
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM