【问题标题】:GET request is not working in React ComponentGET 请求在 React 组件中不起作用
【发布时间】:2017-03-21 13:13:06
【问题描述】:

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

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

【问题讨论】:

  • axios.get(127.0.0.1:8080/get_platforms)的响应是JSON字符串还是JS对象?
  • 你确定console.llog(res.functionality)???请将 res 放在括号中 axios.get(http://127.0.0.1:8080/get_platforms).then((res) => {...}
  • 是一个json字符串

标签: javascript api reactjs get babeljs


【解决方案1】:

问题在于你对响应的处理,你应该使用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

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2016-02-12
    相关资源
    最近更新 更多