我正在尝试向我的 React 组件发出 axiosGET 请求,我在 console.log 上获得了对象。但是当我尝试渲染它时,我得到了 "is not defined"

i'm trying to make a axiosGET request to my react component, i get the object on the console.log. But when i try to render it i get a "is not defined"

//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})
   }

我认为我的请求代码很糟糕,如果有人帮助我解决问题,甚至重构代码以获得更好、更干净的代码。这会很棒。谢谢

你的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
  })

在您的代码中,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/