javascript - 如何从 .then 函数中获取数据
问题描述
试图在 then/catch 语句之外阅读。它在 .then 内部工作正常,但在 react html 内部不起作用
class DashboardPage extends Component {
...
componentDidMount() {
axios.get('http://localhost:3000/users/me', this.yourConfig)
.then(function (response) {
// handle success
console.log(response.data.name)
console.log(response.data.email)
})
....
render() {
return (
<div className="App">
<p>Welcome {this.response.data.name}</p>
<p>Your email is {this.response.data.email}</p>
this is your token {this.tokenCookie}
</div>
);
}
}
解决方案
您需要保存response
到状态。像这样的东西应该工作:
class DashboardPage extends Component {
constructor(props) {
super(props);
this.state = {response: null};
}
...
componentDidMount() {
axios.get('http://localhost:3000/users/me', this.yourConfig)
.then((response) => {
// handle success
console.log(response.data.name)
console.log(response.data.email)
this.setState({ response });
});
}
....
render() {
if (this.state.response == null) {
return (<div className="App"><p>Response not loaded</p></div>); // Whatever you want to render when there is no response yet
} else {
return (
<div className="App">
<p>Welcome {this.state.response.data.name}</p>
<p>Your email is {this.state.response.data.email}</p>
this is your token {this.tokenCookie}
</div>
);
}
}
注意:我将函数 ( function (response)
) 更改为 ES6 箭头函数,以便this
可以使用。您还可以设置一个变量 like并将var that = this
其更改为.this
function (response)
that
推荐阅读
- google-apps-script - 当用户开始输入时计算文档中的单词
- java - HTML 和 CSS 中的 Apache Wicket 实时预览更改
- string - 如何在 Golang 中解决(字符串和字节类型不匹配)
- javascript - 优化排列生成
- c++ - 在 python ctypes 中声明变量并传递给 dll 函数
- python - 将脚本转换为 exe 时键盘模块出现溢出错误
- sql - CONCAT 列 SQL
- reactjs - 刷新页面时在服务器上反应应用程序显示 404 页面
- python - 使用 Boto 访问 S3 文件的 URL
- php - 如何制作动态路由系统?