绝对初学者 React 按钮 Axios

Absolute Beginner React Button Axios

我正在使用 create-react-app and attempting to modify the App.js file to have a button that has an onclick method that makes an axios HTTP request. I have been trying this for a couple weeks and the error I've gotten the most has been unexpected token in my handleClick(e). I tried this,但我不明白为什么它无法编译:

// Example React.js Component

var ButtonComponent = React.createClass({
    getInitialState: function() {
        return {
            numClicks: 0
        }
    }
   click: function() {
        this.setState(numClicks: this.state.numClicks + 1);
    },
    render: function() {
       return  (
        <div>
            <button onClick={this.click.bind(this)}>Click Me</button>  
            {this.state.numClicks}
        </div>
       );
   } 
});

如果有人能提供一些帮助,我将不胜感激。我只想能够呈现可以向我的 Express 应用程序发出请求的组件。

React.createClass 已弃用。使用 ES6 类。在您使用 create-react-app 创建的 React 应用程序的 src/App.js 中尝试以下操作:

class App extends Component {
  onClick() {
    // axios request
  }
  render() {
    return (
      <button onClick={() => this.onClick() }>Axios Request</button>
    );
  }
}

official tutorial 是学习 React 基础知识的好地方。

一旦您开始并熟悉语法,我强烈建议您准备好Sebmarbage's react-basics 解释理论概念。

您使用的是已弃用的语法,请改用 React with ES6。

关于你的问题,你有多个语法错误:

  • getInitialState 右大括号后缺少一个逗号。
  • this.setState()
  • 中缺少大括号
  • 可能你没有导入 react

这是经过更正的代码:

var ButtonComponent = React.createClass({
  getInitialState: function() {
    return {
      numClicks: 0
    }
  },
  click: function() {
    this.setState({ numClicks: this.state.numClicks + 1 });
  },
  render: function() {
    return  (
      <div>
        <button onClick={this.click.bind(this)}>Click Me</button>
        {this.state.numClicks}
      </div>
    );
  }
});

我建议您阅读 documentation/guide 并切换到 ES6。

下面是同样使用 ES6 的代码:

import React, { Component } from 'react';

class ButtonComponent extends Component {

  constructor(props) {
    super(props); 
    this.state = {
      numClicks: 0
    }
  }

  click() {
    this.setState({ numClicks: this.state.numClicks + 1 });
  }

  render() {
    return  (
      <div>
        <button onClick={this.click.bind(this)}>Click Me</button>
        {this.state.numClicks}
      </div>
    );
  }
}