简体   繁体   中英

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

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:

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. 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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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