【发布时间】:2018-09-15 23:25:15
【问题描述】:
我正在尝试在 React 中编写一个组件,该组件将使用 fetch() API 从网站获取数据,然后使用 setState 设置与数据相等的状态,然后最终呈现数据。我的代码如下所示:
import React from 'react';
export default class Test extends React.Component {
constructor(props){
super(props);
this.state = {apiInfo: 'default'};
}
componentDidMount(){
fetch('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(
function(response){
return response.json();
}
).then(function(jsonData){
return JSON.stringify(jsonData);
}
).then(function(jsonStr){
this.setState({apiInfo: jsonStr});
console.log(jsonStr);
});
}
render(){
return(
<tr>
<td>{this.state.apiInfo}</td>
</tr>
);
}
}
但是,这会导致错误提示我无法设置未定义的状态。我最终在我的 HTML 上呈现“默认”。我到底做错了什么?
【问题讨论】:
-
尝试将箭头函数传递给.then
-
你好!所以这行得通,但你能解释一下为什么箭头函数会产生如此大的不同吗?我以为箭头函数和函数的唯一区别是箭头函数没有被提升?
-
箭头函数将 this 绑定到声明上下文而不是执行上下文。
-
更多解释请看 mdn Arrow Function page in "No separate this" 部分
标签: javascript reactjs promise fetch