我正在尝试使用在axios库中的节点中创建的我的api,并钩住useEffect来显示当前项目用户,并且出现错误未捕获(承诺)TypeError:无法读取未定义的属性'recordset',为什么? API
router.get('/api/users, async(req,res)=>{
try {
let results=await m.all();
res.json(results)
} catch (error) {
console.log(error);
res.sendStatus(500);
}
});
数据
{
"recordset": [
[
{
"id":1,
"Name":"Alissa",
"Age": 45,
"Adress": "Brooklyn 405",
"Phone": "212-324-4153"
},
{
"id":2,
"Name":"Ellis",
"Age": 23,
"Adress": "Boston 955",
"Phone": "212-324-4152"
}
],
"output": {},
"rowsAffected": [
2
]
}
使用React钩子useEffect和axios库调用在节点js中创建的API的函数
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
function AllUsers(){
const url='/api/users';
const[user, setuser]= useState({recordset: [] });
useEffect(()=>{
const getUsers=async()=>{
const response =await axios.get(url);
setuser(response.user);
}
getUsers();
},[]);
return(
<ul>
{user.recordset.map(item=>(
<li key={item.id}>
<a href={item.url}>{item.Name}</a>
</li>
))}
</ul>
)
}
export default AllUsers;
答案 0 :(得分:0)
请尝试更改此行:
setuser(response.user);
到
setuser(response);
您的响应数据似乎没有键为user
的对象。
答案 1 :(得分:0)
使用合作伙伴提到的axios的data属性
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
function AllUsers(){
const url='/api/users';
const[user, setuser]= useState({recordset: [] });
useEffect(()=>{
const getUsers=async()=>{
const response =await axios.get(url);
**setuser(response.data);**
}
getUsers();
},[]);
return(
<ul>
{user.recordset.map(item=>(
<li key={item.id}>
<a href={item.url}>{item.Name}</a>
</li>
))}
</ul>
)
}
export default AllUsers;