2016-09-24 292 views

回答

9

取决于你想要做的事情,但这是一个例子。

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

一个好方法也应该是如果您使用react-router从路由器的onEnter api进行ajax调用。

+0

你没有展示如何将它渲染到页面 –

+0

你使用状态渲染到页面中。所以在这里你可以映射'this.state.posts'并获得每个帖子。 @ pixel67是否有意义? – EQuimper

+0

我可以在没有状态的情况下使用它吗?我如何获取这个数据里面.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