node.js - 如何从nodejs渲染图像以使用axios对js做出反应
问题描述
import React, { Component } from "react";
import axios from "axios";
import "./getForm.css";
class GetData extends Component {
state = { posts: [] };
componentDidMount() {
axios
.get("http://localhost:8888/api/v1/user") //returns promise
.then((response) => {
this.setState({ posts: response.data });
console.log("response:", response.data);
})
.catch((err) => {
console.log("err:", err);
});
}
render() {
return (
<>
<h1>Posts</h1>
<table>
<tbody>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>mobile</th>
<th>status</th>
</tr>
{this.state.posts.map((post) => {
return (
<tr key={post.id}>
<td>{post.id}</td>
<td> {post.name}</td>
<td> {post.email}</td>
<td> {post.mobile}</td>
<td>
<img src={post.image} />
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
}
export default GetData;
解决方案
注意:假设您image
的服务器响应中有 URL。
在posts
初始渲染时收到来自服务器的响应之前,正在映射状态。您可以添加一个初始loading
设置为的状态,在该状态设置后,您可以设置为 false。true
response.data
posts
loading
然后,您可以像这样基于此loading
状态有条件地渲染整个组件。
这是一个工作沙箱的链接。
import React, { Component } from "react";
import axios from "axios";
class GetData extends Component {
state = { posts: [], loading: true };
componentDidMount() {
this.fetchUserData();
}
fetchUserData = async () => {
try {
const response = await axios.get("http://localhost:8888/api/v1/user");
this.setState({ posts: response.data, loading: false });
console.log(response.data);
} catch (error) {
this.setState({ loading: false });
console.log(error);
}
};
render() {
if (this.state.loading) {
return "Loading";
}
return (
<>
<h1>Posts</h1>
<table>
<tbody>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
<th>mobile</th>
<th>status</th>
</tr>
{this.state.posts.map((post) => {
return (
<tr key={post.id}>
<td>{post.id}</td>
<td> {post.name}</td>
<td> {post.email}</td>
<td> {post.mobile}</td>
<td>
<img src={post.image} />
</td>
</tr>
);
})}
</tbody>
</table>
</>
);
}
}
export default GetData;
推荐阅读
- javascript - Ember - 多对多关系数据未更新
- java - Spark数据帧过滤(“where”)子句的自定义解释
- node.js - 猫鼬确保文件是唯一的
- firebase - 如何触发 Firebase Cloud Functions 的重试?
- javascript - Vue 完整日历(下一个,上一个)按钮触发
- php - 从数组中获取最小值并删除重复项
- html - 网站背景图片的问题
- javascript - jquery圈子进度| 更改圆圈进度的颜色
- python - 使用步骤高效创建 numpy N 数组
- c# - 如何将 Google 输入的数字字符串转换为整数作为存储到 MySql DB 中?