在 React 渲染中访问嵌套对象

时间:2021-05-22 18:06:11

标签: javascript reactjs object

当我尝试访问 GET 请求返回的数组内的对象时,不知道为什么会出现 TypeError: project.Item is not a function 错误。 这就是我的代码的外观。奇怪的是,有时我使用完全相同的代码没有错误。

   const getProjects = async() => {
  var myHeaders = new Headers();
  myHeaders.set('Authorization', 'Basic ' + credentials);

  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };

  let response;

    try {
        response = await fetch (`${APIlink}/projects/`+ props.match.params.project_uid, requestOptions)
    } catch (err) {
        return;
    }
    const result = await response.json();
    setproject(result);
  }
  console.warn("props", props);
  console.log(project);
  

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


  return (<div>
      <Header />
      <img src={logo}/>
  <h1>Project Title</h1>
    <Row style = {{display: "flex"}}><Col xs="6">{project.Item.profName}</Col>
                 <Col xs="6">{project.Item.dept}</Col>
    </Row>
    <Row style = {{display: "flex"}}><Col xs="6">{project.Item.duration} months</Col>
                 <Col xs="6">INR {project.Item.stipend}</Col>
    </Row>
    <Row style = {{displey: "flex"}}><Col xs="6">{project.Item.totalSlots}</Col>
                 <Col xs="6">Start Date</Col>
    </Row>
    {project.Item.description}
    <br></br>
    {project.Item.responsibilities}
    <br></br>
    

  </div>);

当我发出 GET 请求以获取特定项目的详细信息时,将返回以下对象

{
  "Item": {
    "project-uid": "e50ffdfaad1c4de31d6ad5e82d789c6a",
    "responsibilities": "he standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham",
    "preReq": "Fourth year",
    "addDetails": "The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from de Finibus Bonorum et Malorum by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham",
    "dept": "mechanical",
    "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.",
    "duration": "12",
    "totalSlots": "5",
    "stipend": "10000",
    "profName": "Dr. Aaron Sorkin",
    "user-uid": "7e7199247de1125a6dc1518dd78ba554"
  }
}

1 个答案:

答案 0 :(得分:1)

您的 useEffect 将在组件安装后被调用。因此,如果您的项目初始状态为 null 或 {} 。你会得到一个错误。您可以添加一个名为 loading 的附加状态,一旦 API 调用成功,您可以将其设置为 false。在进行 api 调用时添加加载状态是一个很好的做法。这样我们就可以在未来渲染一个很好的 UX 加载器。

const [ loading, setLoading ] = useState(true);

const getProjects = async() => {
  var myHeaders = new Headers();
  myHeaders.set('Authorization', 'Basic ' + credentials);

  var requestOptions = {
    method: 'GET',
    headers: myHeaders,
    redirect: 'follow'
  };
 
  let response;

    try {
        response = await fetch (`${APIlink}/projects/`+ props.match.params.project_uid, requestOptions)
    } catch (err) {
        return;
    } finally{
      setLoading(false);
     }
    const result = await response.json();
    setproject(result);
  }
  console.warn("props", props);
  console.log(project);
  

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

  if(loading)
    return <h1> Fetching Data ...</h1>

  return (<div>
      <Header />
      <img src={logo}/>
  <h1>Project Title</h1>
    <Row style = {{display: "flex"}}><Col xs="6">{project?.Item?.profName || ''}</Col>
                 <Col xs="6">{project?.Item?.dept || ''}</Col>
    </Row>
    <Row style = {{display: "flex"}}><Col xs="6">{project?.Item?.duration || ''} months</Col>
                 <Col xs="6">INR {project?.Item?.stipend || ''}</Col>
    </Row>
    <Row style = {{displey: "flex"}}><Col xs="6">{project?.Item?.totalSlots || ''}</Col>
                 <Col xs="6">Start Date</Col>
    </Row>
    {project?.Item?.description || ''}
    <br></br>
    {project?.Item?.responsibilities || ''}
    <br></br>
    

  </div>);