无法在axios处于react状态的浏览器中显示mysql查询结果

xwbd5t1u  于 2023-01-25  发布在  iOS
关注(0)|答案(1)|浏览(118)

我尝试从数据库检索数据并在单击按钮时在浏览器中显示它,但我总是收到此错误(Uncaught Error: Objects are not valid as a React child (found: object with keys {studentId, firstName, surName, otherName, state, localGovt, phoneNumber, imgUrl}). If you meant to render a collection of children, use an array instead.)。当我使用console.log时,我能够看到数据,但在DOM中失败。
这是前端的代码。

import Axios from "axios";
import { useState, useEffect } from "react";

const SearchUsers = () => {
  const [input, setInput] = useState("");
  const [studentResult, setStudentResult] = useState([]);

  const handleSearch = async () => {
    //const sanitizedInput = input.trim().toUpperCase();

    try {
      const { data } = await Axios.get("http://localhost:3500/students");
      const { result } = data; // this is an array
      console.log(result)//this works. it displays array of objects with the data from the db
        setStudentResult(result);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      <div className="flex flex-col w-2/4 mx-auto my-20">
        <div>
          <input
            className="input w-full"
            type="text"
            name="search"
            placeholder="Search a Student"
            onChange={(e) => setInput(e.target.value)}
          />
        </div>
        <div className="flex justify-center mt-5">
          <button
            type="button"
            className="btn shadow shadow-gray-500"
            onClick={handleSearch}
          >
            Get All Students
          </button>
        </div>

        <div>
          {studentResult.map((item, index) => {
            return (
              <div key={index}>
                <p>{item.firstName}</p>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};
export default SearchUsers;

这是后端的代码,它是一个从数据库中检索所有数据的控制器函数

const getAllStudents = (req, res) => {
  const selectAll = "SELECT * FROM students";

  studentDB.query(selectAll, (err, result) => {
    res.sendStatus(200).json({ result: result });
  });
};
0kjbasz6

0kjbasz61#

出了什么问题?

在以下情况下会出现问题:
1.用空数组初始化useState,并
1.未定义其类型;
然后,数组的类型将隐式地赋给never[],这意味着数组应该始终为空。
因此,改变该数组(包括通过setStudentResult(newArray))将始终失败。

如何修复

要解决这个问题,我们需要显式定义空数组的类型,例如:

const [studentResult, setStudentResult] = useState<{name: string, grade:number}[]>([]);

您应该根据result的数据结构更改上面的类型声明。
希望有用。干杯。

相关问题