实际使用效果挂钩:TypeError:无法读取未定义的属性'title'

问题描述 投票:-1回答:1

我正在学习react useEffects挂钩,我正在使用JSON占位符作为我的其余API,

我能够显示所有帖子,所有用户等,现在我想使用useEffects显示单个帖子

这是我的解决方法

import React, {useState, useEffect} from 'react';
import axios from 'axios'
function Data(){

const[post, setPost] = useState();

const[id, setId] = useState(1);

useEffect(()=>{
  console.log('call only once');
    axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
    .then(res =>{
      console.log(res);
      setPost(res.data);
    })
    .catch(error=>{
      console.log(error);
    })

}, []);

    return (
      <div>

      <h1> LIst of Posts </h1>
      <input type="text" value={id} onChange={e=>setId(e.target.value)} />

      <div>{post.title}</div>

      </div>
    );

}

export default Data;

现在,当我运行应用程序时,出现以下错误

TypeError: Cannot read property 'title' of undefined

我的代码在做什么错?

javascript html reactjs
1个回答
1
投票

您的代码正在尝试读取尚不存在的对象属性。尝试使用该调用构造具有预定结构的post对象:

© www.soinside.com 2019 - 2024. All rights reserved.