如何使用Axios在React中显示Mongodb中的数据



我在React中显示数据时遇到困难-这是我的代码:

import Axios from 'axios';
import { useNavigate } from 'react-router';

export default function ProductCatalog() {
let navigate = useNavigate();
function addProduct() {
navigate('/adding')
}
const [products, setProducts] = useState([{}])

useEffect(() => {
const axiosProd = async () => {
const response = await Axios('http://localhost:3001/getProducts');
setProducts(response.data)
};
axiosProd();
}, []);
const useProducts = products.map((product)=>{
return <div>
<h1>{product.name}</h1>
</div>
})
return(
<>
<button className = "button" onClick={addProduct}>Add New Product</button>
<br></br>
{useProducts}
</>
)
}

当我点击的链接时,我知道数据是以JSON对象的形式传入的http://localhost:3001/getProducts,我看到了我的数据。我做错了什么?

您应该创建一个函数,然后在函数之外调用use effect。要使用axios执行获取请求,请使用axios.get(api)

例如:

// Get All Shoes
const getShoes = () => {
axios.get('/shoes')
.then(res => setShoes(res.data))
.catch(err => console.log(err));
}

然后

useEffect(() => {
getShoes();
}, [])

最新更新