React,ES6 + 7 ajax调用不起作用?

时间:2016-02-07 03:59:29

标签: javascript reactjs

自从昨天以来,我一直对此感到困惑。我似乎无法通过json-server将数据从本地服务器呈现到我的带有 ES6 + 7 语法的React代码中。我确实用 ES5 的方式尝试了,但没有给我任何结果。

App.js

import React, {Component} from 'react';
import {render} from 'react-dom';

const source = "http://localhost:3000/";

    class App extends Component {

  state = { authors: [] };

  static defaultProps = {
    source: ''
  };

  static propTypes() {
    source: React.PropTypes.string
  };

  loadAuthors() {
      fetch(source)
    .then(response => response.json())
    .then(data => this.setState({ authors: data }))
    .catch(err => console.error(source, err.toString()))
  }

  componentDidMount() {
    this.loadAuthors()
  }

  render() {
    const renderData = this.state.authors.map(function(author) {
      return (
        <div>
        <p>author.id</p>
        <p>author.firstName</p>
        <p>author.lastName</p>
        </div>
      )
    });
    return (
      <div>
        <h1>
          Welcome to the react starter!
        </h1>
        <h1>
          {renderData}
        </h1>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

JSON来源

{
  authors: [
    {
      id: "zarghon-shah",
      firstName: "Zarghon",
      lastName: "Shah"
    },
    {
      id: "khpalwalk-pashtun",
      firstName: "Khpalwalk",
      lastName: "Pashtun"
    },
    {
      id: "sazinda-khudai",
      firstName: "Sazinda",
      lastName: "Khudai"
    }
  ]
}

提前致谢

1 个答案:

答案 0 :(得分:1)

看起来您需要在对“author”的引用周围放置JSX花括号,以便插值正确发生:

button.addTarget(self, action: ControlSelector.clearTapped, forControlEvents: .TouchUpInside)

否则你只是写出文字字符串“author.id”等。