【问题标题】:ComponentDidMount issue in React for rest apiReact for rest api 中的 ComponentDidMount 问题
【发布时间】:2020-03-06 16:34:12
【问题描述】:

我正在尝试从 rest api 检索数据。我正在尝试记录结果,但没有任何结果,到目前为止我的代码是:

反应

import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React', 
      awsApiData: [],
    };
  }

 componentDidMount() {
        console.log('app mounted');
        fetch('https://nc1fi4y2i7.execute-api.eu-west-2.amazonaws.com/api/data')
            .then(data => data.json())
            .then(data => this.setState({awsApiData: data.home}, () => console.log(data.home)))
    }

  render() {
    return (
      <div>
        <p>
          Start editing to see some magic happen :)
        </p>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

api 架构

{
  "home": [
    {
      "title": "John Doe title",
      "body": "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.",
      "image": "image/example.jpg"
    }
  ],
  "about": [
    {
      "title": "John is the main part 1",
      "body": "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.",
      "image": "image/example.jpg"
    }
  ]
}

有什么想法吗?

【问题讨论】:

  • API 可能失败。也可以执行 .catch 来获取承诺。
  • 另外,如果有的话,从你的控制台添加日志
  • 控制台中没有任何记录

标签: javascript reactjs api


【解决方案1】:

CORS 策略是否有可能阻止资源?在操作数据之前尝试使用 console.log 调试它

尝试:https://www.test-cors.org/ 结果:FAILED:跨域请求被阻止:同源策略不允许读取位于https://nc1fi4y2i7.execute-api.eu-west-2.amazonaws.com/api/data 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)

【讨论】:

  • 不,因为我已经测试了 api,它给出了 200 ok 响应
  • @Sole,你确定吗?检查此codesnadbox 它在 chrome 控制台及其CORS 中显示错误,沙箱中的代码有效。
  • 嗯,我已经检查了reqbin.com,我没有遇到任何问题。
  • 我不知道 reqbin 但他们可能使用后端技术来获取您的网址。尝试test-cors.org(由于 CORS 原因,您的网址在该网站上失败)
  • 谢谢,凯文,我已经检查过了,这似乎是一个问题。所以我需要先修复 CORS
【解决方案2】:

由于CORS 问题,AWS API 请求不适用于此codesandbox,以下是codesandbox 上的工作示例,您渲染也没有做任何事情来渲染从 API 调用中检索到的数据.

但这是一个带有硬编码数据的工作 sn-p:

import React, { Component } from "react";

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "React",
      awsApiData: {}
    };
  }

  componentDidMount() {
    console.log("Did mount");
    // fetch("https://nc1fi4y2i7.execute-api.eu-west-2.amazonaws.com/api/data")
    //   .then(data => data.json())
    //   .then(data => this.setState({ awsApiData: data.home }));
    const awsApiData = {
      home: [
        {
          title: "John Doe title",
          body:
            "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.",
          image: "image/example.jpg"
        }
      ],
      about: [
        {
          title: "John is the main part 1",
          body:
            "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.",
          image: "image/example.jpg"
        }
      ]
    };
    this.setState({ awsApiData });
  }

  render() {
    const data = this.state.awsApiData;
    return (
      <div>
        {Object.keys(data).map(e => {
          return <div>{data[e][0].title}</div>;
        })}
      </div>
    );
  }
}

【讨论】:

    【解决方案3】:

    您的渲染方法只返回一些静态标记。 当前 fetch 调用正在使用名称 awsApiData 带来数据并存储在状态中。 但即便如此,您也必须在渲染方法中显示该数据。

    state = {
     data : []
    }
    
    componentDidMount = () => {
      this.setState({data: [1,2,3,4,5]})
    }
    render () {
      return (
    
       <div>
        {this.state.data.map((ele, index) => <p key={index} > {ele}</p>}
    
      </div>
      )
    }
    

    只要这个状态被this.setState 函数改变,react 就会用新数据重新渲染。

    【讨论】:

      【解决方案4】:
      1. 您能在控制台中看到“已安装应用程序”吗?
      2. 您能否在浏览器的网络选项卡中看到 API 实际返回某些内容并且正在运行的结果?
      3. 如果是这样,请尝试仅通过控制台记录数据(删除 setState 语句:仅用于验证)

      4. 从反应文档中,为了设置状态,我们需要为 setState() 提供一个回调函数作为第一个参数

        this.setState(() =>return{awsApiData:data.home}})

      或者只是..

      this.setState({awsApiData:data.home})
      

      不建议这样做

      【讨论】:

        猜你喜欢
        • 2019-08-20
        • 1970-01-01
        • 2019-04-17
        • 1970-01-01
        • 2019-05-19
        • 1970-01-01
        • 2020-08-17
        • 1970-01-01
        相关资源
        最近更新 更多