来自数据库的数据在状态中显示,但在React.js中不显示在屏幕上

时间:2020-04-19 14:59:13

标签: javascript reactjs

我是刚接触并设计电子商务网站的新手。在网站的管理端,我创建了一个数据库来存储客户信息。我可以写入数据库并从中读取数据(数据显示在状态中),但是我无法在屏幕上显示数据。我有一个名为“ displayCustomerList”的函数,用于从状态中获取数据并对其进行格式化,但是在“渲染”部分中,什么都没有显示。任何帮助或建议,我们将不胜感激。

import React, { Component } from "react";
import Title from "./Title";
import { Link, Redirect } from "react-router-dom";
import { ButtonContainer } from "./Button";
import axios from "axios";

export default class Admin extends Component {

constructor(props) {
    super(props);
    const token = localStorage.getItem("token");

    let loggedIn = true;
    if (token == null) {
      loggedIn = false;
    }

    this.state = {
      loggedIn,
      name: "",
      address: "",
      postcode: "",
      phone: "",
      posts: [],
    };
  }

  componentDidMount = () => {
    this.getCustomerList();
  };

  getCustomerList = () => {
    axios
      .get("/api")
      .then((response) => {
        const data = response.data;
        this.setState({ posts: data });
        console.log("Data has been received");
      })
      .catch(() => {
        alert("Error retrieving data");
      });
  };

  handleChange = ({ target }) => {
    const { name, value } = target;
    this.setState({ [name]: value });
  };

  submit = (event) => {
    event.preventDefault();

    const payload = {
      name: this.state.name,
      address: this.state.address,
      postcode: this.state.postcode,
      phone: this.state.phone,
    };

    axios({
      url: "/api/save",
      method: "POST",
      data: payload,
    })
      .then(() => {
        console.log("Data has been sent to the server");
        this.resetUserInputs();
        this.getCustomerList();
      })
      .catch(() => {
        console.log("Internal server error");
      });
  };

  resetUserInputs = () => {
    this.setState({
      name: "",
      address: "",
      postcode: "",
      phone: "",
    });
  };

//THIS IS CAUSING THE ISSUE
  displayCustomerList = (posts) => {
    if (!posts.length) return null;

    console.log(posts) // I can see the array in the console

    posts.map((post, index) => (
      <div key={index} className="customer.list_display">
        <h3>TEST</h3> //NOT DISPLAYING
        <h3>{post.name}</h3>
        <p>{post._id}</p>
        <p>{post.address}</p>
        <p>{post.postcode}</p>
        <p>{post.phoneNumber}</p>
      </div>
    ));
  };

  render() {
    console.log("State: ", this.state);

    if (this.state.loggedIn === false) {
      return <Redirect to="/login" />;
    }

    return (
      <React.Fragment>
        <div className="py-5">
          <div className="container">
            <Title name="Admin" />
            <Link to="/">Logout</Link>
          </div>
        </div>
        <div className="card-footer d-flex justify-content-between">
          <form onSubmit={this.submit} className="py-5">
            <div className="form-input">
              <input
                type="text"
                name="name"
                placeholder="Name"
                value={this.state.name}
                onChange={this.handleChange}
                className="nameInput"
              />
            </div>
            <div className="form-input">
              <input
                type="address"
                name="address"
                placeholder="Address"
                value={this.state.address}
                onChange={this.handleChange}
                className="addressInput"
              />
            </div>
            <div className="form-input">
              <input
                type="text"
                name="postcode"
                placeholder="Postcode"
                value={this.state.postcode}
                onChange={this.handleChange}
                className="postcodeInput"
              />
            </div>
            <div className="form-input">
              <input
                type="text"
                name="phone"
                placeholder="Phone number"
                value={this.state.phone}
                onChange={this.handleChange}
                className="phoneInput"
              />
            </div>
            <ButtonContainer>submit</ButtonContainer>
          </form>
        </div>

        <div>
          {/* <CustomerList /> */}
          <Title name="Customer List" />
        </div>

        //NOTHING IS BEING DISPLAYED
        <div className="blog-">
          {this.displayCustomerList(this.state.posts)}
        </div>

      </React.Fragment>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

您应该像这样从displayCustomerList返回JSX对象:

displayCustomerList = (posts) => {
if (!posts.length) return null;

console.log(posts) // I can see the array in the console

return posts.map((post, index) => (
  <div key={index} className="customer.list_display">
    <h3>TEST</h3> //NOT DISPLAYING
    <h3>{post.name}</h3>
    <p>{post._id}</p>
    <p>{post.address}</p>
    <p>{post.postcode}</p>
    <p>{post.phoneNumber}</p>
  </div>
));

};