Javascript API函数调用在react组件中不起作用
我从API获取数据的函数不起作用Javascript API函数调用在react组件中不起作用,javascript,reactjs,react-router,fetch-api,Javascript,Reactjs,React Router,Fetch Api,我从API获取数据的函数不起作用 import React, { Component } from 'react' class Contact extends Component{ constructor(){ super() this.state = { data: [] } this.fetchData = this.fetchData.bind(this) } fetchD
import React, { Component } from 'react'
class Contact extends Component{
constructor(){
super()
this.state = {
data: []
}
this.fetchData = this.fetchData.bind(this)
}
fetchData(){
let base_url = 'https://jsonplaceholder.typicode.com/photos/'
fetch(base_url, {method:"GET"})
.then(response => response.json())
.then(json => {
this.setState({
data:json
})
})
console.log(this.state.data)
}
render(){
return(
<div>
<h1>Contact page{this.state.data.title}</h1>
</div>
)
}
}
export default Contact
import React,{Component}来自“React”
类接触扩展组件{
构造函数(){
超级()
此.state={
数据:[]
}
this.fetchData=this.fetchData.bind(this)
}
fetchData(){
让base_url=https://jsonplaceholder.typicode.com/photos/'
fetch(base_url,{method:“GET”})
.then(response=>response.json())
。然后(json=>{
这是我的国家({
数据:json
})
})
console.log(this.state.data)
}
render(){
返回(
联系页面{this.state.data.title}
)
}
}
导出默认联系人
首先,您没有在任何地方调用fetchData
函数。在componentDidMount
方法中调用它
其次,数据应该是一个数组,所以this.state.data.title
会抛出错误
最后,状态更新将反映在下一个渲染周期中,因此记录console.log(this.state.data)
不会显示更新的数据
类联系人扩展了React.Component{
构造函数(){
超级()
此.state={
数据:[]
}
this.fetchData=this.fetchData.bind(this)
}
componentDidMount(){
这是fetchData();
}
fetchData(){
让base_url=https://jsonplaceholder.typicode.com/photos/'
fetch(base_url,{method:“GET”})
.then(response=>response.json())
。然后(json=>{
这是我的国家({
数据:json
})
})
}
render(){
返回(
联系页面
{this.state.data.map(photo=>{photo.title}}
)
}
}
ReactDOM.render(,document.getElementById('app'))代码>
请添加更多详细信息,如您收到的错误消息等。可能您必须使用映射功能,因为您的状态“数据”是数组