我在api中有一个ajax函数,我正在使axios从我的反应js组件获取请求。我如何访问返回的数据以在网页上显示它。如何访问从axios返回的数据使用react js显示在网页上?
回答
取决于你想要做的事情,但这是一个例子。
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是否有意义? – EQuimper
我可以在没有状态的情况下使用它吗?我如何获取这个数据里面.then()? –
以下是使用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
- 1. React Js Axios发布请求不从网页api返回机构
- 2. 远程访问mongodb数据并在网页上显示结果?
- 3. 如何使用AJAX在网页上显示动态数据
- 4. React js嵌套axios调用
- 5. 从函数返回Axios Promise
- 6. 如何从我的网站上的Facebook对话框访问返回数据?
- 7. 如何使用React Table和Axios进行API调用并将其显示在React JS中?
- 8. 如何在另一个axios中使用axios响应获取React JS?
- 9. 如何使用$ q.all(承诺)并在网页上显示回复?
- 10. 如何从Java方法返回后访问返回数据
- 11. 使用Dojo数据网格在JSP页面上显示数据
- 12. 如何在React JS中使用Redux和Axios?
- 13. 显示JS数组网页
- 14. 使用React访问多维数组js
- 15. 如何从Vue.js返回Laravel中的数据Axios
- 16. 如何从python的数据返回到PHP和PHP页面上显示
- 17. 如何访问jQuery.ajax()的返回数据
- 18. React - 在返回的数据中访问嵌套对象
- 19. 在网页上实时显示数据
- 20. 全球访问数据REACT JS
- 21. 循环访问表数据React JS
- 22. 访问:在报告上显示数据
- 23. 如何在我的网页上显示来自JSON的数据?
- 24. 如何在HTML网页上显示JS变量的值?
- 25. 使用Python从网页的Ajax调用返回数据
- 26. 在console.log中使用角度返回数据但在HTML页面上不显示
- 27. 如何在网页上显示来自API的数据
- 28. 在我的网站上显示唯一/返回的用户数
- 29. 在Facebook上显示网页
- 30. 访问页面后不显示数据
在哪里你在componentDidMount()中做了ajax调用? – EQuimper