【问题标题】:Data not getting displayed from fetching from an api从 api 获取数据未显示
【发布时间】:2020-04-03 12:09:30
【问题描述】:

首先我在 states 中声明了一个 empy 数组:

但是数据没有显示它显示一些错误:

将状态设置为时也会显示错误

Unhandled Rejection (TypeError): undefined is not an object (evaluating 'this.setState')

它指向 setState 线 谁能解决这个问题

【问题讨论】:

  • 您不需要 JSON.stringify(jsonData) 因为它将 JavaScript 对象或值转换为 JSON 字符串。如果你 console.log(jsonStr) 你会明白我的意思,然后你尝试访问一个字符串的 .course_title。
  • 这个问题有什么更新吗?我的回答解决了你的问题吗?如果是这样,请将我的回答标记为已接受。

标签: javascript node.js reactjs mongodb ecmascript-6


【解决方案1】:

我不明白你为什么在这里使用 JSON.stringify

return JSON.stringify(jsonData);

因为你已经在这里把你的数据转换成json了

 return response.json();

同样调用 API 来获取数据是使用 componentDidMount 生命周期钩子。尝试像这样更改您的代码

componentDidMount() {
        fetch('http://localhost:3000/"my end point in api"')
            .then(function(response) {
                return response.json();
            })
            .then(function(jsonStr) {
                this.setState({ CourseTitle: jsonStr.course_title });
            });
    }

【讨论】:

  • 嘿,托尼,我无法验证您的答案是否有效,我尝试放置 console.log,但没有显示任何内容。可能我认为我不能在正确的地方使用 console.log 你可以编辑你的代码把 console.log 或任何其他方法,以便我可以验证答案
【解决方案2】:

根据官方文档,componentWillMount 已被贬值,请尝试在 componentDidMount 中调用它。

componentDidMount(){
   fetch('http://localhost:3000/"my end point in api"')
        .then(function(response) {
            return response.json();
        }).then(function(jsonData) {
            return JSON.stringify(jsonData);
        })
        .then(function(jsonStr) {
            this.setState({ CourseTitle: jsonStr.course_title });
            alert(jsonStr.course_title);
        });

 }

在打印时,输入一个条件 console.log("正在打印",this.state.courseTitle?this.state.courseTitle:"尚未获取")

【讨论】:

    【解决方案3】:

    不明白你为什么要像帖子中提到的那样获取而不是这样......

         componentDidMount() {
            fetch('http://localhost:3000/"my end point in api"')
                .then(function(response) {
                    return response.json();
                })
                .then(function(jsonStr) {
                    this.setState({ CourseTitle: jsonStr.course_title });
                    alert(jsonStr.course_title);
                });
        }
    

    并在渲染前控制您的数据

    并且建议按照Reactjs的官方文档在componentDidMount生命周期方法中调用api

    【讨论】:

      【解决方案4】:

      三件事:

      尽量听从别人的建议,把componentWillMount改成componentDidMount

      此外,请遵循删除 JSON.stringify(jsonData) 的建议,因为您正在将对象转换为字符串,然后您尝试访问对象属性(它们不存在)。

      最后,JavaScript 中的一个常见错误是在不同的上下文中误解this 的含义是什么。比如看下sn-p:

      const obj = {
        say() {
          console.log(this.toString());
        },
        sayDelayed() {
          setTimeout(function() {
            console.log(this.toString());
          }, 500);
        }
      };
      
      obj.say();
      obj.sayDelayed();

      如您所见,setTimeout 中的this 不再引用该对象,这是因为setTimeout 正在引用另一个对象(很可能window 在非严格模式下)。

      在您的情况下,fetch 中的this 不再引用class。尝试在执行fetch之前将class的作用域存储在一个变量中,并使用这个变量而不是this来调用setState。检查下一个sn-p:

      const obj = {
        fetch() {
          const myObject = this;
          fetch('https://jsonplaceholder.typicode.com/todos/1')
            .then(function(response) {
              return response.json();
            })
            .then(function(jsonStr) {
              console.log('wrong this', this.toString());
              console.log('right this', myObject.toString());
            });
        }
      };
      
      obj.fetch();

      你需要把你的代码重构成这样:

      componentDidMount() {
          const cls = this;
          fetch('http://localhost:3000/"my end point in api"')
              .then(function(response) {
                  return response.json();
              })
              .then(function(jsonStr) {
                  cls.setState({ CourseTitle: jsonStr.course_title });
              });
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-13
        • 1970-01-01
        • 2018-11-10
        • 2017-08-15
        • 1970-01-01
        • 1970-01-01
        • 2022-01-15
        • 2020-11-22
        相关资源
        最近更新 更多