Redux add form
On a blog has demonstrated the corresponding data, reference Redux quick start , this section will add data using a form.
1, the new PostFrom.js in components
- Add content, and the corresponding constructor
- Want to show, it is necessary to introduce into App.js, and used in the div
View Code
//PostFrom.js
import React, {Component} from 'react';
class PostForm extends Component {
constructor(props){
super(props);
this.state = {
}
}
render() {
return (
添加内容
);
}
}
export default PostForm;
//App.js
······
import PostForm from "./components/PostForm";
······
{/*使用 */}
{/*使用 */}
2, back PostForm.js code written form
- add div inside the form tag, add an event, onSubmit method
- Continues to form inside add div, write two label, 1 Ge button
- Binding of corresponding states, binding events, the binding value
- Binding to this event
- Write method just added
View Code
import React, {Component} from 'react';
class PostForm extends Component {
constructor(props){
super(props);
this.state = {
//绑定对应状态
title:"",
body:""
}
//绑定this
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
//方法
onChange(e){
//方法里面空着的话,浏览器页面不能写入数据
this.setState({ [e.target.name]:e.target.value});
}
onSubmit(e){
}
render() {
return (
添加内容
);
}
}
export default PostForm;
3、
- Write this part of onSubmit
- Request data, and the contents entered into the form in which data to
View Code
onSubmit(e){
e.preventDefault(); //阻止默认事件
const post = { //拿到状态
title:this.state.title,
body:this.state.body
};
fetch("http://jsonplaceholder.typicode.com/posts",{
method:"POST",
headers:{
"content-type":"application/json"
},
body:JSON.stringify(post)
})
.then(res => res.json()) //成功的话,返回数据,并进行json解析
.then(data => console.log(data)) //打印日志
}
- Normal to get the data: