我是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'));
并获取以下错误列表:
编译失败
./ src / index.js 语法错误:意外令牌(7:7)
6 | App类扩展了React.Component {
7 | axios.get('http://example.com/api/api/topCardNews')
8 | .then(function(response){
9 | //处理成功
10 | console.log(response);
This error occurred during the build time and cannot be dismissed.
答案 0 :(得分:2)
将调用函数放在构造函数或componentDidMount函数之内
library(dplyr)
iris %>%
group_by(Species)
# A tibble: 150 x 5
# Groups: Species [3]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# <dbl> <dbl> <dbl> <dbl> <fct>
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3 1.4 0.2 setosa
# 3 4.7 3.2 1.3 0.2 setosa
# 4 4.6 3.1 1.5 0.2 setosa
答案 1 :(得分:1)
您应该在生命周期事件(例如ComponentWillMount)或构造函数中调用axios.get(.....)。
类组件可以具有声明或函数定义以及render。它不能直接调用函数。
答案 2 :(得分:0)
问题是我必须在任何Javascript event
或constructor()
中使用此api代码。
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import ApiContent from './ApiContent';
class App extends React.Component{
constructor(props){
super(props);
axios.get('http://example.com/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'));