【发布时间】:2017-02-02 11:52:30
【问题描述】:
我在 api 中有 ajax 函数,我从我的 react js 组件发出 axios get 请求。如何访问返回的数据以将其显示在网页上。
【问题讨论】:
-
您在 componentDidMount() 中进行 ajax 调用的位置?
我在 api 中有 ajax 函数,我从我的 react js 组件发出 axios get 请求。如何访问返回的数据以将其显示在网页上。
【问题讨论】:
取决于您尝试做什么,但这是一个示例。
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 这有意义吗?
这是使用 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
【讨论】: