首页 > 解决方案 > 如何从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;

标签: node.jsreactjsapiaxiosrender

解决方案


注意:假设您image的服务器响应中有 URL。

posts初始渲染时收到来自服务器的响应之前,正在映射状态。您可以添加一个初始loading设置为的状态,在该状态设置后,您可以设置为 false。trueresponse.datapostsloading

然后,您可以像这样基于此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;

推荐阅读