投掷"意外标记“;错误,当我在reactjs中使用jsopapi时

Throwing "unexpected token" error, when i use jsop api in reactjs?

本文关键字:reactjs jsopapi 意外 quot 错误 投掷      更新时间:2023-09-26

当我过去从json-api获取数据时,它抛出了"意外令牌"错误。下面,我添加了我迄今为止尝试过的代码。让我离开这个问题。我一直在努力解决这个问题。

这里,

var Demo = React.createClass({
    render: function() {
        getInitialState:function(){
            return {
                data:[]
            };
        },
        componentDidMount: function () {
            $.ajax({
              url: "http://www.w3schools.com/angular/customers.php"
            }).done(function(data) {
              this.setState({data: data})
            });
        },
        return (
            <div>
                {this.props.data.map(function(el,i) {
                    return <div key={i}>
                        <div>{el.Name}</div>
                        <div>{el.City}</div>
                        <div>{el.Country}</div>
                    </div>;
                }
            </div>
        );
    }
});
var Stream = React.createClass({
  render: function() {
    return (
        <div>
            <div className="scrollContent ">
                <Demo />
            </div>
        </div>
    );
  }
});

您的代码中有几个错误

  1. render方法中移动getInitialStatecomponentDidMount,这些方法应该是组件(Demo)类的子级,而不是render方法的子级
  2. dataType: 'json'添加到$.ajax,因为现在它返回字符串,但在您的情况下,您需要获得json
  3. 当您在.done中使用this.setState时,您应该将this设置为.done回调,因为现在this指的是$.ajax对象,而不是Demo,您可以使用.bind方法来执行此操作
  4. this.props.data更改为this.state.data,因为位于状态对象中的数据不在道具中
  5. 数据位于records属性中的数组使用它,而不是仅使用data

Example

var Demo = React.createClass({
  getInitialState:function() {
    return {
      data :[]
    };
  },
  componentDidMount: function () {
    $.ajax({
      url: "http://www.w3schools.com/angular/customers.php",
      dataType: 'json'
    }).done(function(response) {
      this.setState({ data: response.records });
    }.bind(this));
  },
  render: function() {
    var customers = this.state.data.map(function(el,i) {
      return <div key={i}>
        <div>{el.Name}</div>
        <div>{el.City}</div>
        <div>{el.Country}</div>
      </div>
    });
    return <div>{ customers }</div>;
  }
});