【发布时间】: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