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

标签 javascript reactjs react-redux react-router axios

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

相关文章:

reactjs - Next Redux Wrapper 中的水合物作用是什么?

Javascript:如何使控件在方法中发送自身

javascript - Protractor - 分配给 element.all.locator.count 的变量返回 NaN 为什么?

javascript - 从 Promise 设置对象数组

javascript - 飞行前响应中的 Access-Control-Allow-Methods 不允许方法 PATCH

javascript - react + 终极版 : submit multi-component form

javascript - 不处理 dojo 请求之前的 Dojo 方面

javascript - 使用 React 在每两个元素之后创建新的 ul

reactjs - 如何为调用 props 中接收的函数的函数添加单元测试

javascript - React-bootstrap-autosuggest 的问题