axios 在渲染函数中尝试console.log时,从API检索到数组的数据更改其值(react tsx)

9lowa7mx  于 2022-12-23  发布在  iOS
关注(0)|答案(2)|浏览(99)

我有一个程序,它能够从我创建的API中检索数据,使用以下与后端交互的组件:

import React, { Fragment, useEffect, useState } from 'react'
import { Button, Stack } from '@mui/material';
import TabsComponent from './TabsComponent';
import axios from 'axios';
import { getIssues } from '../../API';
import IssueApiData from '../../../../backend/types/issue.type.d'
import IssueInterface from '../../../../backend/types/IssueInterface'
type Props = {}
// TODO: create context for current rendered component?
// TODO: Add to API.ts file the axios requests to clean component

function Issues({ }: Props) {
  const [issuesList, setIssuesList] = useState<IssueInterface[]>([]); // we retrieve from DB issues - we need it to look the same object's structure
  const [hasLoaded, setHasLoaded] = useState(false);
  useEffect(() => {
    setHasLoaded((prev) => false)
    try {
      axios({
        method: 'get',
        url: 'http://localhost:8001/api/issues',
        headers: { 'Content-type': "application/json" }
      }).then((response) => {
        setIssuesList((prev: any[]) => response.data.issues.map((issue: IssueInterface) =>
          prev.push(issue)))
        console.log(issuesList)
        setHasLoaded((prev) => true)
      })
    } catch (err) {
      console.log("error : " + err);
    }

  }, [])

  return (
    <Fragment>
      <>{console.log(issuesList)}</>
      <Stack>

        <h1>hi</h1>
        {hasLoaded ? issuesList.map((issue: IssueInterface) => <div><h1>company: {issue.company_name}</h1></div>) : <></>}

      </Stack>
    </Fragment>
  )
}

export default Issues

这使得我的页面看起来像这样:

这不是我所期望呈现的(因为我希望company_name属性也被打印出来)。
现在,奇怪的是,我在开始时接收到第25行打印的正确数据,然后它更改了值,如第36行所示(呈现函数中的console.log):

后端:

router.route("/api/issues").get(getAllIssues);

export const getAllIssues = async (
  req: Request,
  res: Response
): Promise<void> => {
  try {
    const issues: IssueInterface[] = await Issue.find({});
    res.status(200).json({ issues });
  } catch (err) {
    throw err;
  }
};

我不知道为什么会发生这样的事情。谢谢你的帮助。

s6fujrry

s6fujrry1#

你可以看到,最初的问题长度是0,所以当你试图通过Map访问元素时,你会得到undefined,这是正常的。
相反,您可以在访问元素之前进行检查,方法是将?添加到.,使其变为?.

hasLoaded ? issuesList?.map((issue: IssueInterface) => <div><h1>company: {issue?.company_name}</h1></div>) : <></>}
wtlkbnrh

wtlkbnrh2#

setIssuesList((prev: any[]) => response.data.issues.map((issue: IssueInterface) => prev.push(issue)))
console.log(issuesList)

你应该知道在第25行,你的console.log打印列表的上一个值,状态值在下一次表单呈现后改变,把console.log移到useEffect后面就可以看到

相关问题