我对诺言很陌生,我使用json占位符构建了一个简单的应用程序。由于某种原因,我的数据响应不正确,我无法弄清原因。
console.log(data) // returns {id: 101} It should return {title: 'xx', body: 'xx'
我已经花了大约一个小时来查询这个问题,我是否有语法错误?还是我想念一些文档?任何帮助将不胜感激,请参阅下面的代码。
import React from 'react';
class PostForm extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
body: ''
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
onSubmit(event) {
event.preventDefault();
const post = {
title: this.state.title,
body: this.state.body
};
// console.log(post) // returns title: 'xxx', body: 'xxx';
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
haders: {
'Content-type': 'application/json; charset=UTF-8'
},
body: JSON.stringify(post)
})
.then(res => res.json())
.then(data => console.log(data)) // this returns {id: 101} It should return my post object with the inputs from the form fields;
}
render() {
const { title, body } = this.state;
return (
<div>
<h1>Add Post</h1>
<form onSubmit={this.onSubmit}>
<div>
<label>Title</label>
<br />
<input
type="text"
name="title"
value={title}
onChange={this.onChange}
/>
</div>
<div>
<label>Title</label>
<br />
<textarea
name="body"
value={body}
onChange={this.onChange}
/>
</div>
<div>
<input type="submit" name="submit" />
</div>
</form>
</div>
);
}
}
export default PostForm;
非常感谢您的帮助。非常感谢。