2016-09-24 294 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