【发布时间】:2020-08-20 14:36:29
【问题描述】:
博客.js
import React, { useState, useEffect } from "react"
import Axios from "axios"
const Home = () => {
const [blog, setBlog] = useState([])
useEffect(() => {
loadBlog()
}, [])
const loadBlog = async () => {
await Axios.get(`http://localhost:3001/api/blog/get`)
.then((res) => {
console.log(res.data.data)
setBlog(res.data.data)
console.log(blog)
})
.catch((err) => {
console.log(err)
})
}
return (
<>
<div className="container">
<div className="col-lg-10">
<h2> React CRUD Operation </h2>
</div>
<div className="col-lg-2">
<button> Add Blog </button>
</div>
<table className="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Picture</th>
<th>Title</th>
<th>Short Description</th>
<th>Author</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>{blog.id}</td>
<td>
<img src={"../../../public/logo512.png"} alt="not available" />
</td>
<td>{blog.title}</td>
<td>{blog.short_desc}</td>
<td>{blog.author}</td>
<td>
<button>Edit</button> <button>Delete</button>{" "}
</td>
</tr>
</tbody>
</table>
</div>
</>
)
}
export default Home
我正在从 API 获取数据并获取数据。数据很好,但它没有进入 setBlog Hook。当我控制台响应时,它很好并且数据被成功获取,但问题是它没有进入 setBlog 挂钩。我是新手,不知道为什么它没有进入 setBlog 挂钩。任何帮助将不胜感激
【问题讨论】:
-
blog是一个对象还是一个对象数组? -
您是否基于
console.log(blog)没有反映您通过setBlog发布的博客这一事实? -
我试图解释
setState在这个答案中的工作原理;希望你觉得它有用。你不是唯一一个感到困惑的人:stackoverflow.com/a/62460109/119549 -
它是对象数组
-
是的,当我想使用 blog.something 时它甚至无法正常工作
标签: javascript reactjs axios react-hooks