【问题标题】:How to fetch an API response in React?如何在 React 中获取 API 响应?
【发布时间】:2020-06-25 03:12:30
【问题描述】:

我正在尝试在 ReactJS 中获取以下 API 响应数据。我不知道该怎么做..有人可以帮我吗?在此先感谢您,我真的很感谢您提供的任何帮助或建议。

对于我的最终输出,我希望最终循环数组中的每个响应,并像 API 响应一样显示它们,除了在一个表中表示每个商店的地址和邮政详细信息。

API 响应

[
  {
    title: 'Paragon',
    address: '290 Orchard Road #B1-03 Singapore 238859',
    postal: '238859'
  },
  {
    title: 'BreadTalk IHQ',
    address: '30 Tai Seng Street #01-02 Singapore 534013',
    postal: '534013'
  },
  {
    title: 'City Square Mall',
    address: '180 Kitchener Road #01-10 Singapore 208539',
    postal: '208539'
  }
]

代码(details.js)

class Crawler extends React.Component {

// Create constructor with props
constructor(props) {
    super(props);

    // Create a state that takes in the SEEDURL
    this.state = {
        seedURL: '',
        response: null,
        error: null
    };
}

    // The seed url taken from the input
    const seedURL = this.state;

    // Take the seedURL and send to API using axios
    const url = "/api";

    // Send data using axios
    axios.defaults.headers.post['Content-Type'] ='application/x-www-form-urlencoded';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
    try {
        // Axios takes in the url and SeedURL
        axios
        .post(url, seedURL)
            .then((res) => {
                this.setState({response: res, error: null})
            })
            .catch((err) => {
                this.setState({error: err, response: null})
            });
    } catch (e) {
        console.log(e);

render() {
    return(
        // How do i read the response here?
    );
}
}

【问题讨论】:

  • 您是否尝试过安慰来自 api 的响应?我想你会进入 res.data 然后你可以 setState 它进入响应状态。

标签: reactjs api


【解决方案1】:

你可以使用componentDidMount生命周期钩子来获取组件挂载的api数据并更新状态。 state 更新将呈现具有更新状态的组件。

除了class fields,您不能直接在类主体中添加代码。您应该将代码包装在方法中。

示例:

class Crawler extends React.Component {
  // Create constructor with props
  constructor(props) {
    super(props);
    this.state = {
      seedURL: 'http://localhost:5000',
      response: [],
      error: null
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  async fetchData() {
    const seedURL = this.state.seedURL;
    const url = "/api";
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
    try {
      let res = await axios.post(seedURL + url);
      let data = await res.json();
      console.log(data);
      this.setState({ response: data, error: null })
    } catch (error) {
      console.log(error);
      this.setState({ error: error.message, response: [] })
    }
  }
  render() {
    return (
      <div >
        <table>
          <thead>
            <tr>
              <th>title</th>
              <th>address</th>
              <th>postal</th>
            </tr>
          </thead>
          <tbody>
            {(this.state.response.length > 0) ? this.state.response.map(item => (
              <tr key={item.title + item.postal}>
                <td>{item.title}</td>
                <td>{item.address}</td>
                <td>{item.postal}</td>
              </tr>
            )) : null}
          </tbody>
        </table>
      </div>
    );
  }
}

【讨论】:

  • 你能检查一下网络标签吗,你得到什么回应。
  • 它的 localhost:5000/api,我对我的 react js 文件做了一个控制台日志。我目前正在使用快递,不知道为什么控制台日志只出现在我的express backend 一侧而不是我的react frontend
  • 天哪,我做了一个控制台日志res.data 我没有在我的frontend 上检索任何内容。我在backend 做了一个日志,不过我似乎还不错。
  • 我不知道怎么写,但它有 500 行代码。简而言之,我在后端有两个post api。第一个 api 工作得很好。但是第二个api似乎没有发送任何数据,我使用res.end(JSON.stringify(data));发送上面的API响应
【解决方案2】:

试试这个-

render() {
    return(<React.Fragment>
{this.state.response && this.state.response.map((r, i)=> <div key={i}>
              <div>{r.title}</div>
              <div>{r.address}</div>
              <div>{r.postal}</div>
          </div>)}
</React.Fragment>
);
}
}

【讨论】:

  • 我尝试了 response.map.. 但我之前遇到了同样的错误。 TypeError: this.state.response.map is not a function
  • 使用控制台记录 outpot。响应的到来有一些不同的结构。它不是一个数组看起来像
  • @scorezel789 几天前我遇到了同样的错误,map 函数适用于数组对象,这就是您收到此错误的原因。检查您的代码,您必须在错误的 json 对象上应用 map 函数。
【解决方案3】:

--试试这个代码--

class Crawler extends React.Component {
    constructor(props) {
        super(props);

        // Create a state that takes in the SEEDURL
        this.state = {
            seedURL: '',
            error: null,
            responses: []
        };
    }

    // The seed url taken from the input
    const seedURL = this.state;

    // Take the seedURL and send to API using axios
    const url = "/api";

    // Send data using axios
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
        try {
    // Axios takes in the url and SeedURL
    axios
        .post(url, seedURL)
        .then((res) => {
            this.setState({ responses: res, error: null })
        })
        .catch((err) => {
            this.setState({ error: err, response: null })
        });
        } catch (e) {
            console.log(error);
      this.setState({ error: error.message, response: [] })
    }

    render() {
        const { responses } = this.state;
        return (
            <div >
                <table>
                    <thead>
                        <tr>
                            <th>title</th>
                            <th>address</th>
                            <th>postal</th>
                        </tr>
                    </thead>
                    <tbody>
                        {responses.map(response =>
                            <tr key={response.title - response.postal}>
                                <td>{response.title}</td>
                                <td>{response.address}</td>
                                <td>{response.postal}</td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
        );
    }
}

【讨论】:

  • 我相信您的代码应该可以工作,但我不确定为什么会收到此错误TypeError: Cannot read property 'map' of undefined。这段代码对你有用吗?
  • 请检查您的 json 响应如下。 axios .post(url, seedURL) .then((res) => { this.setState({ 响应: res, error: null }) console.log(res); }) .catch((err) => { this .setState({ error: err, response: null }) console.log(err); });
【解决方案4】:

要添加到以前的响应中,您将在其中找到如何循环数据,请在您的 package.json 中添加一个代理属性以及您的服务器位置

“代理”:“http://localhost:5000/api

然后只使用 /api 之后的所有请求......例如:从 http://localhost:5000/api/cats 获取数据只需对 /cats 进行获取

同时检查网络标签的 chrome 并确保您的请求正在发送

【讨论】:

  • 嗨胡安!感谢您强调需要做的事情!我发现了我的错误。原来我的回应没有通过前端。我做了控制台日志并设法修复了错误。我一直在传递一个空数组(:
  • 很高兴听到......我们都会犯错......睡觉有助于xD
猜你喜欢
  • 1970-01-01
  • 2018-12-30
  • 2017-12-01
  • 1970-01-01
  • 2021-06-14
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
相关资源
最近更新 更多