尝试读取 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>
);
}
}
最佳答案
您需要将响应
保存到状态。像这样的东西应该有效:
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
。您还可以设置像 var that = this
这样的变量,并将 function (response)
中的 this
更改为 that
。
关于javascript - 如何从 .then 函数中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56976581/