【问题标题】:How do I access data returned from an axios get to display on a web page using react js?如何使用 react js 访问从 axios get 返回的数据以显示在网页上?
【发布时间】:2017-02-02 11:52:30
【问题描述】:

我在 api 中有 ajax 函数,我从我的 react js 组件发出 axios get 请求。如何访问返回的数据以将其显示在网页上。

【问题讨论】:

  • 您在 componentDidMount() 中进行 ajax 调用的位置?

标签: reactjs axios


【解决方案1】:

取决于您尝试做什么,但这是一个示例。

componentDidMount() {
  axios
    .get(`endpoint`)
    .then(res => this.setState({ posts: res.data }))
    .catch(err => console.log(err))
}

如果您使用 react-router 通过路由器的 onEnter api 进行 ajax 调用,这也是一个好方法。

【讨论】:

  • 您使用状态渲染到页面中。所以在这里你可以映射this.state.posts 并获取每个帖子。 @pixel67 这有意义吗?
  • 我可以在没有状态的情况下使用它吗?我如何在 .then() 中获取这些数据?
【解决方案2】:

这是使用 React 和 ES2015 的一种方法。 您需要在构造函数中设置默认状态,并像下面的示例一样发出 get 请求。只需切换名称以使其与您的应用程序一起使用。然后映射您从获取请求的响应中返回的数组。当然更改名称和样式以满足您的需要,我使用 Bootstrap 使事情易于理解。希望这会有所帮助。

  import React, { Component } from 'react'
  import axios from 'axios';
  import cookie from 'react-cookie';
  import { Modal,Button  } from 'react-bootstrap'
  import { API_URL, CLIENT_ROOT_URL, errorHandler } from '../../actions/index';

  class NameofClass extends Component {

      constructor(props) {
        super(props)

        this.state = {
          classrooms: [],
          profile: {country: '', firstName: '', lastName: '', gravatar: '', organization: ''}
        }
      }
      componentDidMount(){
        const authorization = "Some Name" + cookie.load('token').replace("JWT","")
          axios.get(`${API_URL}/your/endpoint`, {
            headers: { 'Authorization': authorization }
          })
          .then(response => {
            this.setState({
              classrooms:response.data.classrooms,
              profile:response.data.profile
            })
          })
          .then(response => {
            this.setState({classrooms: response.data.profile})
          })
          .catch((error) => {
            console.log("error",error)
          })
      }
      render () {
        return (
          <div className='container'>
            <div className='jumbotron'>
              <h1>NameofClass Page</h1>
              <p>Welcome {this.state.profile.firstName}  {this.state.profile.lastName}</p>
            </div>
            <div className='well'>
               {
                 this.state.classrooms.map((room) => {
                    return (
                      <div>
                        <p>{room.name}</p>
                      </div>
                    )
                 })
               }
            </div>
          </div>
        )
      }
    }

    export default NameofClass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 2018-02-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 2021-06-26
    • 2019-09-15
    相关资源
    最近更新 更多