gpt4 book ai didi

javascript - react axios.get 不工作它说编译失败

转载 作者:行者123 更新时间:2023-11-30 11:07:00 24 4
gpt4 key购买 nike

我是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com