在下面的代码中,我从API获取数据,并希望在页面上显示它。
import React, { useState, useEffect } from "react";
import '../all.css';
import Axios from "axios";
const AllProduct = () => {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const { data } = await Axios.get(
"http://localhost:8080/api/QueryAllProducts"
);
console.log(data.response);
setProducts(data.response);
console.log(products);
};
const display = () => {
return (products || []).map(product => (
<tr key={product.id}>
<th>{product.id}</th>
<th>{product.name}</th>
<th>{product.area}</th>
<th>{product.ownerName}</th>
<th>{product.cost}</th>
</tr>
) );
}
useEffect(() => {
fetchProducts();
}, []);
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Area</th>
<th>Owner Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
{display()}
</tbody>
</table>
</div>
)
}
export default AllProduct;
我几乎做了我在stackoverflow上找到的所有方法,但仍然无法解决错误。在前端,我使用ReactJS和后端,我使用NodeJS
这是我得到的错误的屏幕截图
早先,当想要为变量分配默认值时,常见的模式是使用逻辑OR操作符(||):
let foo;
// foo is never assigned any value so it is still undefined
let someDummyText = foo || 'Hello!';
然而,由于||是一个布尔逻辑运算符,左边的操作数被强制为一个布尔值进行计算,并且不返回任何假值(0,",NaN, null, undefined)。如果您认为0、"或NaN是有效值,这种行为可能会导致意想不到的后果。
我建议将您的||操作符更改为??如:
(products ?? [])
因为这个'?? ?
如果你想知道更多,请点击这里:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
我认为您面临的挑战来自您的显示功能。您应该在映射产品之前返回一个Jsx元素,并将映射函数括在大括号({})中,以便React知道您现在正在编写javascript。因此,您可能需要像下面这样重新编写显示函数:
const display = () => {
return (<React.Fragment>
{(products || []).map(product => (
<tr key={product.id}>
<th>{product.id}</th>
<th>{product.name}</th>
<th>{product.area}</th>
<th>{product.ownerName}</th>
<th>{product.cost}</th>
</tr>}))
</React.Fragment>
);
}
我也认为你应该使用<td>{product.name}</td>...
来返回表数据,而不是<th>{product.name}</th>