【问题标题】:Returning result from API and displaying it using react从 API 返回结果并使用 react 显示
【发布时间】:2020-10-29 16:57:23
【问题描述】:

我有一个基本的 React 应用程序,我想显示连接到我的数据库的 API 的结果。

我目前有一个调用我的 api 的 fetch 方法,在控制台中我可以看到它具有来自数据库的正确数据,但我不知道如何在反应中显示它,你能帮忙吗?我有以下代码:

import React, { useEffect, useState } from 'react';

function DisplayCases(props) {

  const [appState, setAppState] = useState({
    loading: false,
    repos: null,
  });

  useEffect(() => {
    setAppState({ loading: true });
  const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "<my api url>" ;
fetch(proxyurl + url) 
      .then((res) => res.json())
      .then(contents => console.log(contents))
      .then((repos) => {
        setAppState({ loading: false, repos: repos });
      });
  }, [setAppState]);


  return (
      <div className='container'>
        <h1>Welcomme {props.location.state}, here are your open cases:</h1>
    <p> {appState.repos}</p>
    </div>
  );
}

export default DisplayCases;

目前

appState.repos 根本不显示任何内容,但 (contents => console.log(contents)) 确实包含我想要显示的信息(“案例”包括客户姓名客户姓氏等)我希望它显示为如果可能,请列出。

【问题讨论】:

    标签: reactjs return state react-props webapi


    【解决方案1】:

    最好只在发生 异步 操作时创建另一个 .then,否则会引入更多语法噪音和类似这样的潜在错误。由于console.log 不返回任何内容,本节:

    .then(contents => console.log(contents))
    .then((repos) => {
      setAppState({ loading: false, repos: repos });
    });
    

    console.log 的返回值传递给下一个.then,即undefined。改为:

    .then((repos) => {
      console.log(repos);
      setAppState({ loading: false, repos: repos });
    });
    

    或者,更好的是,完全删除 loading 属性,然后检查 repos 是否存在,如果您以后需要这样做。

    const [repos, setRepos] = useState();
    // ...
    .then(res => res.json())
    .then(setRepos)
    .catch(handleErrors); // don't forget to handle errors
    // ...
    
    <p> {repos}</p>
    

    请记住,如果功能组件状态与单独的事物相关,则通常应尽可能将它们分离为单独的变量 - 相反,使用单个主状态变量有点反模式。

    【讨论】:

      猜你喜欢
      • 2021-09-28
      • 1970-01-01
      • 2021-01-04
      • 2018-03-08
      • 2021-06-17
      • 1970-01-01
      • 2013-01-22
      • 2020-05-05
      • 1970-01-01
      相关资源
      最近更新 更多