【问题标题】:Throwing "unexpected token" error, when i use jsop api in reactjs?当我在 reactjs 中使用 jsop api 时抛出“意外令牌”错误?
【发布时间】:2016-03-25 05:42:47
【问题描述】:

当我过去从 json api 获取数据时,它会抛出“Unexpected token”错误。下面,我添加了我迄今为止尝试过的代码。让我摆脱这个问题。我一直在努力解决这个问题。

这里,

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>
    );
  }
});

【问题讨论】:

    标签: javascript html json reactjs


    【解决方案1】:

    您的代码中有几个错误

    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>;
      }
    });
    

    【讨论】:

    • 伟大的解释和伟大的贡献..rocking
    • @亚历山大。谢谢你兄弟。
    猜你喜欢
    • 1970-01-01
    • 2018-09-10
    • 2014-01-21
    • 1970-01-01
    • 2022-10-09
    • 2019-08-09
    • 1970-01-01
    • 2019-02-19
    • 2017-10-07
    相关资源
    最近更新 更多