我是 React 的新手。我正在尝试使用 axios 获取我的 api 数据。但是出现错误。我的代码是:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import ApiContent from './ApiContent';
class App extends React.Component{
axios.get('http://example.com/api/api/topCardNews')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
render() {
return(
<div className="asdfs">
<ApiContent />
</div>
);
}
}
ReactDOM.render(<App />,document.getElementById('root'));
并获取错误列表:
Failed to compile
./src/index.js Syntax error: Unexpected token (7:7)
6 | class App extends React.Component{
7 | axios.get('http://example.com/api/api/topCardNews')
8 | .then(function (response) {
9 | // handle success
10 | console.log(response);
This error occurred during the build time and cannot be dismissed.
最佳答案
将调用函数放在构造函数或 componentDidMount 函数中
class App extends React.Component{
constructor(props) {
super(props);
axios.get('http://example.com/api/api/topCardNews') //...
}
componentDidMount(){
//or here or to other lifecycle function based on needs
}
render() {
return(
<div className="asdfs">
<ApiContent />
</div>
);
}
}
关于javascript - react axios.get 不工作它说编译失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55189298/