从api提取后无法显示数据

时间:2019-12-10 10:21:07

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

首先,我在状态内部声明了一个empy数组:

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

在将状态设置为

时也会显示错误
Unhandled Rejection (TypeError): undefined is not an object (evaluating 'this.setState')

,它指向setState行 有人可以解决这个问题吗?

4 个答案:

答案 0 :(得分:3)

我不明白您为什么在这里使用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 });
            });
    }

答案 1 :(得分:0)

根据官方文档,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(“ printing”,this.state.courseTitle?this.state.courseTitle:“尚未获取”)

答案 2 :(得分:0)

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

componentDidMount

并在渲染前对数据进行控制

根据Reactjs的官方文档,建议在{{1}}生命周期方法中调用api

答案 3 :(得分:0)

三件事:

尝试遵循其他人的建议,将componentWillMount更改为componentDidMount

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

最后,在不同上下文中误解JavaScript的含义是this的常见错误。例如,看一下下一个片段:

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

obj.say();
obj.sayDelayed();

如您所见,this内的setTimeout不再引用该对象,这是因为setTimeout引用了另一个对象(最可能是window严格模式)。

对于您而言,this中的fetch不再引用class。在执行class之前,尝试将fetch的范围存储在变量中,并使用此变量而不是this来调用setState。检查下一个代码段:

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 });
        });
}