【问题标题】:Unable to display entries: TypeError: Cannot read properties of undefined (reading 'map') in reactjs无法显示条目:TypeError:无法在 reactjs 中读取未定义的属性(读取“地图”)
【发布时间】:2021-12-16 06:01:43
【问题描述】:

我正在尝试显示来自后端的一些条目。如果我通过 Postman 传递数据,则数据完美地传递到数据库。但是,我无法在前端显示它们。这是我的代码

export default function EntriesDisplay() {

    const [entry,setEntry] = useState([]);
    const [update, setUpdate] = useState(false);

useEffect(function() {
        fetch("http://localhost:8000/api/entries")
        .then((res) => {
            console.log(res.data);
            setEntry(res.data)
        })
        .catch((err)=>{
            console.log(err);
        })
    }, [update])

return(
        <>
                <ul className="list-container">
                    {entry.map((data) => (
                        <EntriesCard
                            data={data}
                            handleEdit={handleEdit}
                            handleDelete={handleDelete}
                        />
                    ))}
                </ul>

这里是组件EntriesCard

function EntriesCard({data, handleEdit, handleDelete}) {
    const{_id, title, link, description} = data;

    return(
        <li key={_id}>
            <div className="title-description">
                <h3>{title}</h3>
                <h2>{link}</h2>
                <p>{description}</p>
            </div>
            <div className="button-container">
                <button className="button" name={_id} onClick={handleEdit}>
                    Edit
                </button>
                <button className="button" name={_id} onClick={handleDelete}>
                    Delete
                </button>
            </div>
        </li>
    )
}

这是代码的后端

app.get('/api/entries', asyncHandler(async (req, res) => {
    const entries = await Entry.find();
    res.json(entries);
})
)

【问题讨论】:

  • console.log(res.data); 的输出是什么?它是一个数组吗?似乎状态已更新为类似于数组的对象以外的其他内容。
  • 如何找到它的输出?我还应该链接后端部分吗?
  • 就在useEffect钩子里,查看浏览器开发工具的控制台日志。
  • 它被称为“未定义”
  • 我已经在问题中添加了后端。

标签: reactjs react-hooks mern


【解决方案1】:

好的,感谢您确认回复内容。它是 JSON,所以你需要“解包”它。假设 JSON data 仍然是您需要存储在 state 中的数组,检查 ok 响应并返回 response.json() Promise 并继续链接。

useEffect(function() {
  fetch("http://localhost:8000/api/entries")
    .then(response => {
      if (!response.ok) throw new Error("response not ok");
      return response.json();
    })
    .then((data) => {
      console.log(data);
      setEntry(data);
    })
    .catch((err)=>{
      console.log(err);
    });
}, [update]);

【讨论】:

    【解决方案2】:

    你应该使用res.json()来解析返回的json数据。

    useEffect(function() {
        fetch("http://localhost:8000/api/entries")
        .then(res => res.json())
        .then((data) => {
            console.log(data);
            setEntry(data)
        })
        .catch((err)=>{
            console.log(err);
        })
    }, [update])
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2018-02-08
      • 2020-04-20
      • 2020-11-18
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2021-12-06
      相关资源
      最近更新 更多