【问题标题】:TypeError: Cannot read property 'title' of undefined ReactjsTypeError:无法读取未定义 Reactjs 的属性“标题”
【发布时间】:2021-04-22 12:45:20
【问题描述】:

我不知道为什么我有这个错误!! 第一次我没有任何错误和它的工作但是当我刷新页面时我有这个错误: TypeError: Cannot read property 'title' of undefinedTypeError: 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>
    )
}

内容.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>
    )
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    问题就在这里:

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

    这里 post 对象将从 axios 调用中获取数据,并且需要一些时间来获取数据,这意味着在初始渲染时 title 将不存在。因此,您必须检查并仅在可用时访问该密钥。

    尝试类似:

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

    或者你也可以试试conditional rendering

    【讨论】:

      【解决方案2】:

      您可以改为执行以下操作:

      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
      }
      

      【讨论】:

      • 感谢您的帮助和解释
      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 2022-07-22
      • 2020-09-12
      • 2019-05-07
      • 2020-07-30
      • 1970-01-01
      相关资源
      最近更新 更多