//component
const Clientslist = () => {
const classes = useStyles()
axios.get('/api/clients').then(resp => {
const {clients} = resp.data
console.log(clients) // i get the data on the terminal
})
return(
...
{
clients.map(client => ( //clients is not defined
<Grid key={client._id} item xs={12} sm={6} md={4}>
<Card
clientName={client.clientName}
...
)
}
//controller
const get = async (req, res) => {
await dbConnect()
const clients = await ClientsModel.find()
res.status(200).json({ success: true, clients})
}
我覺得我的請求代碼很差,如果有人幫助我解決問題,甚至重構代碼以獲得更好、更干凈的代碼。那會很好。謝謝。
uj5u.com熱心網友回復:
您的clients變數是在 axios 回呼的范圍內定義的,不能從外部訪問,但是如果您對其進行了一些修改,則可以將其保存在本地狀態變數中,例如:(3 個新行標有//***)
//component
const Clientslist = () => {
const classes = useStyles()
//*** Adding clients var with initial value as empty array
const [clients, setClients] = useState([]) //***
axios.get('/api/clients').then(resp => {
const {clients} = resp.data
console.log(clients) // i get the data on the terminal
setClients(clients) //*** this would save the new clients in the sate
})
uj5u.com熱心網友回復:
在您的代碼中,clients 變數位于 axios 的本地范圍內,因此無法在 return 陳述句中訪問。當您使用 React 函式式組件時,我們可以使用 useState 鉤子來幫助我們跟蹤變數的狀態
//component
import React, { useState } from 'react';
const Clientslist = () => {
const classes = useStyles();
const [clients, setClients] = useState([]);// empty array denotes initial state
axios.get('/api/clients').then(resp => {
const {clients} = resp.data
console.log(clients)
setClients(clients); // sets the state of variable clients to the received data
})
return(
...
{
clients.map(client => (// updated clients can be used here to display .Also check for the valid response before mapping
<Grid key={client._id} item xs={12} sm={6} md={4}>
<Card
clientName={client.clientName}
...
)
}
有用的資源: https ://reactjs.org/docs/hooks-state.html https://www.geeksforgeeks.org/what-is-usestate-in-react/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482099.html
標籤:javascript 反应 axios 下一个 获取请求
上一篇:物件方法將代碼作為字串回傳
