React请求远程数据
首先下载:
npm install -save axios
import axios from 'axios'
componentDidMount() {
axios.post('http://localhost:3000/albums')
.then((res) => {
console.log('获取成功'+JSON.stringify(res))
})
.catch((error) => {
console.log('获取失败'+error)
})
console.log(' componentDidMount 组件挂载完成的时刻')
}
fetch/GET
定义posts 数组
this.state = {
posts:[]
}
componentDidMount 组件挂载Dom后执行一次
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(res => res.json())
.then(data => this.setState({
posts:data
}))
}
map =>循环遍历数据
render() {
const postItems = this.state.posts.map(post => (
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))
return (
<div>
<h1>Posts</h1>
{postItems}
</div>
);
}
fetch/POST
向接口中添加数据
this.state = {
title: '',
body:''
}
onChange={this.onChange.bind(this) 绑定输入框事件
onSubmit={this.onSubmit.bind(this) 绑定表单按钮事件
render() {
return (
<div>
<h1>添加内容</h1>
<form onSubmit={this.onSubmit.bind(this)}>
<label >title</label>
<input type="text" name="title" onChange={this.onChange.bind(this)} value={this.state.title}></input>
<label>body</label>
<input type="text" name="body" onChange={this.onChange.bind(this)} value={this.state.body}></input>
<button type ="submit">添加</button>
</form>
</div>
);
}
获得输入框中的数据
onChange(e) {
this.setState({
[e.target.name]: e.target.value
})
}
点击按钮将输入框数据添加到接口中
onSubmit(e) {
e.preventDefault();
const post = {
title: this.state.title,
body: this.state.body,
};
console.log(this.state.title)
console.log(this.state.body)
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"content-type": "application/json"
},
body:JSON.stringify(post)
})
.then(res => res.json())
.then(data=>console.log(data))
}
网友评论