axios
1.安裝 axios模塊
npm install axios --save
1
2.引用 哪裏使用引哪裏
import axios from 'axios'
1
3.使用
import React, {Component} from 'react'
import axios from 'axios'
class Axios extends Component {
constructor(props) {
super(props);
this.state = {
list:[]
};
}
// 請求數據
//componentDidMount
getData=()=>{
axios.get('http://jsonplaceholder.typicode.com/posts').then(res=>{
console.log(res.data)
this.setState({
list:res.data
})
})
}
render() {
return (
<div>
<div>
<button onClick={this.getData}>點擊獲取數據</button>
</div>
{
this.state.list.map((item,key)=>{
return(
<p key={key}>{item.title}</p>
)
})
}
</div>
);
}
}
export default Axios;
fetchJSONP
1.安裝 fetchJSONP模塊
npm install fetch-jsonp --save
2.引入 哪裏使用引哪裏
import fetchJsonp from 'fetch-jsonp'
3.使用
fetchJsonp 請求數據的時候,數據能打印出來,但是在循環渲染的時候出現
Uncaught (in promise) TypeError: Cannot read property ‘map’ of undefined
暫未解決,希望知道這個問題的告知我一下,
import React, {Component} from 'react'
import fetchJsonp from 'fetch-jsonp'
class FetchJsonp extends Component {
constructor(props) {
super(props);
this.state = {
list:[]
};
}
getData=()=>{
fetchJsonp('http://jsonplaceholder.typicode.com/posts').then(res=>{
return res.json();
}).then((json)=>{
console.log(json)
this.setState({
list:json.data,
})
})
}
render() {
return (
<div>
<button onClick={this.getData}>fetchJsonp請求數據</button>
<div>
{
this.state.list.map((item,key)=>{
return(
<p key={key}>{item.title}</p>
)
})
}
</div>
</div>
);
}
}
export default FetchJsonp;
如果有問題,可以加我微信一起討論,我們一起進步!
屏幕前的你,加油!