GET请求在React组件中不起作用

时间:2017-03-21 13:13:07

标签: javascript api reactjs get babel

我已导入axios库和React。我正在React组件中进行调用,请求是正确的并且还返回响应,它给了我:

{"functionality": [
         {"category": "", "price": 2.0, "moltiplicator": 100.0, "name": "Plat"}
  ]
}

但是当我设置对状态变量的响应时,它不起作用,这是代码:

export class FetchDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    axios.get(`http://127.0.0.1:8080/get_platforms`)
      .then(res => {
        this.setState({
            posts: res.functionality
          });
      });
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.posts.map(post =>
            <li >{post.category}</li>
          )}
        </ul>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

问题在于您处理回复,您应该使用res.data,而不仅仅是res

export class FetchDemo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    axios.get(`http://127.0.0.1:8080/get_platforms`)
      .then(res => {
        this.setState({
            posts: res.data.functionality
          });
      });
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.posts.map(post =>
            <li >{post.category}</li>
          )}
        </ul>
      </div>
    );
  }
}

更新:请参阅axios的示例:https://github.com/mzabriskie/axios/blob/master/examples/get/index.html