我正在尝试使用MERN堆栈制作一个电子商务应用程序,因此我必须从服务器请求一些数据并将其保存为状态,但是当我调用set函数时,React不会更新状态。 / p>
如果您对此问题有疑问,请在评论中写上他们,
import React, { useState, useEffect, Fragment } from 'react';
import { config } from '../../config/config'
import axios from 'axios'
import Sidebar from '../../components/Sidebar'
const Products = () => {
const [sidebarOpen, setSidebarOpen] = useState(false);
const [categories, setCategories] = useState([])
async function getCategories() {
const data = await axios({
method: 'get',
url: `http://${config.SERVER_URL}:${config.SERVER_PORT}/api/categories/byBusiness/id`
})
console.log(data) // Logs [{...},{...}]
return data
}
useEffect(() => {
async function getCatHandler(){
const categoriesReq = await getCategories()
setCategories(categoriesReq)
console.log(categories) //Logs [], it should log [{...},{...}]
}
getCatHandler()
}, [])
return (
<Fragment>
<Container fluid className="dashboard-container">
<Row className="dashboard-row">
<Sidebar isOpen={sidebarOpen} isOpenHandler={isOpenHandler}/>
<Col className="dashboard-col-1">
<div className="dashboard-navbar">
<div className="nav-container">
Username
</div>
<div className="nav-toggler" onClick={() => setSidebarOpen(true)}>
<GiHamburgerMenu/>
</div>
</div>
<div className="dashboard-content">
<div className="dashboard-title">
<div>
<p>Dashboard</p>
<p>Productos</p>
</div>
</div>
{categories.map((e) => {
return (
<div className="dashboard-table">
a
</div>
)
})}
</div>
</Col>
</Row>
</Container>
</Fragment>
);
};
export default Products;